![](/img/trans.png)
[英]NotificationCenter is not working from AppDelegate in Swift iOS
[英]NotificationCenter not working in didSelectRowAt in iOS Swift 3
您好我想将通知发送到另一个这样的视图控制器:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
NotificationCenter.default.post(name: Notification.Name("thisIsTestNotif"), object: nil)
}
因此,在viewDidLoad中进行设置:
NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)
以及以下内容:
func thisistestHandler(notification:Notification) {
}
但它不起作用。 主要问题是在didSelectRow方法中设置调用方法时产生的。
请帮助我解决此问题。
您的观察者的选择器错误。 您的通知观察者方法采用参数,但未在选择器参数中为该方法添加观察者时指定该参数。 项目正在编译的事实意味着必须存在另一个具有相同名称但没有参数的方法。
改成:
override func viewDidLoad() {
............
............
NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler(notification:)),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)
}
@objc func thisistestHandler(notification:Notification) {
}
最可靠且兼容ObjC的Swift 3语法是
#selector(thisistestHandler(_:))
和
func thisistestHandler(_ notification: Notification) {...
当然,通知的接收者必须已经加载。
注意:
如果控制器相关,则协议/委托或闭包回调是更好的选择。 仅在可以有多个接收者或发送者和接收者无关的情况下,才应使用Notification
。
代替viewDidLoad
加
NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)
在viewWillAppear
,并删除观察员viewWillDisappear
。
请尝试不确定,但可能对您有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.