是的,Notification 可以做你想做的事。在视图控制器中,发布通知:
class YourViewController: UIViewController {
...
@IBAction func buttonPressed(_ sender: Any) {
NotificationCenter.default.post(name: "ViewControllerButtonPressed", object: nil)
}
}
然后,在您的 AppDelegate 中,添加一个 Notification 观察者来观察此通知名称的帖子:
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
...
//Add the observer
//This observer will call the "doSomething" function every time NotificationCenter.default.post(name: "ViewControllerButtonPressed", object: nil) is called
NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: "ViewControllerButtonPressed", object: nil)
}
@objc func doSomething() {
print("A button was pressed in one of your view controllers!")
}
}
补充建议:
为了让事情更简单,您可以扩展 Notification.Name 来为名称创建静态 String 值:
public extension Notification.Name {
static let ButtonPressed = Notification.Name("ViewControllerButtonPressed")
}
这可以替换
NotificationCenter.default.post(name: "ViewControllerButtonPressed", object: nil)
与
NotificationCenter.default.post(name: NSNotification.Name.ButtonPressed, object: nil)
和
NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: "ViewControllerButtonPressed", object: nil)
与
NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: NSNotification.Name.ButtonPressed, object: nil)
实现上述方法是可选的,但可以防止在使用Notifications 时出现拼写错误。