简体   繁体   English

NotificationCenter在iOS Swift 3中的didSelectRowAt中不起作用

[英]NotificationCenter not working in didSelectRowAt in iOS Swift 3

Hello I wanna send notification to another view controller like this: 您好我想将通知发送到另一个这样的视图控制器:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    NotificationCenter.default.post(name: Notification.Name("thisIsTestNotif"), object: nil)
}  

Thus set this in viewDidLoad: 因此,在viewDidLoad中进行设置:

NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)  

and in the following: 以及以下内容:

func thisistestHandler(notification:Notification)  {
}

but it does not work. 但它不起作用。 The main problem is accrue when set call method in didSelectRow method. 主要问题是在didSelectRow方法中设置调用方法时产生的。

Please help me to fix this problem. 请帮助我解决此问题。

The selector for your observer is wrong. 您的观察者的选择器错误。 Your notification observer method takes parameter, you have not specified that while adding observer for that method in the selector parameter. 您的通知观察者方法采用参数,但未在选择器参数中为该方法添加观察者时指定该参数。 The fact that your project is compiling means there must be another method with the same name but with no parameters. 项目正在编译的事实意味着必须存在另一个具有相同名称但没有参数的方法。

Change to: 改成:

override func viewDidLoad() {
    ............
    ............

    NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler(notification:)),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)
}

@objc func thisistestHandler(notification:Notification)  {

}

The most reliable – and ObjC compatible – Swift 3 syntax is 最可靠且兼容ObjC的Swift 3语法是

#selector(thisistestHandler(_:))

and

func thisistestHandler(_ notification: Notification)  {...

Of course the receiver of the notification must have been loaded already. 当然,通知的接收者必须已经加载。


Note: 注意:

If the controllers are related then protocol / delegate or closure callback are the better choice. 如果控制器相关,则协议/委托或闭包回调是更好的选择。 A Notification is supposed to be used only if there can be multiple receivers or sender and receiver are not related. 仅在可以有多个接收者或发送者和接收者无关的情况下,才应使用Notification

Instead of viewDidLoad 代替viewDidLoad

Add

NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)  

in viewWillAppear and remove observer in viewWillDisappear . viewWillAppear ,并删除观察员viewWillDisappear

Just try not sure but might be work for you. 请尝试不确定,但可能对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM