How do you create custom notifications in Swift 3?

前端 未结 13 676
自闭症患者
自闭症患者 2020-12-04 09:07

In Objective-C, a custom notification is just a plain NSString, but it\'s not obvious in the WWDC version of Swift 3 just what it should be.

13条回答
  •  北海茫月
    2020-12-04 09:31

    I did my own implementation mixing things from there and there, and find this as the most convenient. Sharing for who any that might be interested:

    public extension Notification {
        public class MyApp {
            public static let Something = Notification.Name("Notification.MyApp.Something")
        }
    }
    
    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(self.onSomethingChange(notification:)),
                                                   name: Notification.MyApp.Something,
                                                   object: nil)
        }
    
        deinit {
            NotificationCenter.default.removeObserver(self)
        }
    
        @IBAction func btnTapped(_ sender: UIButton) {
            NotificationCenter.default.post(name: Notification.MyApp.Something,
                                          object: self,
                                        userInfo: [Notification.MyApp.Something:"foo"])
        }
    
        func onSomethingChange(notification:NSNotification) {
            print("notification received")
            let userInfo = notification.userInfo!
            let key = Notification.MyApp.Something 
            let something = userInfo[key]! as! String //Yes, this works :)
            print(something)
        }
    }
    

提交回复
热议问题