An example of the use of the notification center of NotificationCenter in Swift

  • 2020-05-30 21:10:42
  • OfStack

preface

This paper mainly introduces the relevant content about the use of Swift notification center (NotificationCenter). NotificationCenter is a class in Swift that schedules message notification. It adopts singleton pattern design to realize the functions of transferring value and callback.

Notifications are powerful, and they are a great way to transfer information between two unrelated controllers. So, without further ado, let's take a look at how to use them.

1. Add notifications


  ///  Notice of 
  let notificationName = "XMNotification"
  ///  Custom notification 
  NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name(rawValue: notificationName), object: nil)

2. Set the monitoring method


 ///  Method callback after receiving notification 
 @objc private func notificationAction(noti: Notification) {
  ///  Gets the location of the keyboard / highly / The time interval ...
  print(noti)
 }

3. Destroy in time after the notice is used up


 ///  The destructor . Similar to the OC the  dealloc
 deinit {
  ///  Remove the notification 
  NotificationCenter.default.removeObserver(self)
 }

4. Send notifications


 ///  Send simple data 
 NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "XMNotification"), object: "Hello 2017")

 ///  Send extra data 
 let info = ["name":"Eric","age":21] as [String : Any]
 NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "XMNotification"), object: "GoodBye 2016", userInfo: info)

The use of notification in the system, monitoring keyboard changes


  ///  The notification center listens for keyboard changes 
  #selector(notificationAction), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)

Other notification names for the keyboard


  public static let UIKeyboardWillShow: NSNotification.Name
  ///  The keyboard is displayed 
  public static let UIKeyboardDidShow: NSNotification.Name
  ///  The keyboard is going to be hidden 
  public static let UIKeyboardWillHide: NSNotification.Name
  ///  Keyboard hidden 
  public static let UIKeyboardDidHide: NSNotification.Name
  ///  The keyboard is going to change its own frame
  public static let UIKeyboardWillChangeFrame: NSNotification.Name
  ///  The keyboard frame Change to complete 
  public static let UIKeyboardDidChangeFrame: NSNotification.Name

conclusion


Related articles: