Swift 新手。我在下面有两个片段:
NotificationCenter.default.addObserver(self,
selector:#selector(ViewController.notificationReceived),
name: Notification.Name(rawValue: name), object: nil)
@objc func notificationReceived(notification:Notification){
let x = notification.userInfo!
print("\(x["name"]!)")
}
最后
let x:UITapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapped))
self.addGestureRecognizer(x)
func tapped(){
print("tapped")
self.delegate!.theViewTapped()
}
为什么 notificationCenter
?我应该提供 @objc
selector
的标签参数但不适用于 UITapGestureRecognizer
Action 参数?
Selector
之间到底有什么区别?和 Action in
swift ?
最佳答案
检查此 Swift 4 提案: SE-0160 Limiting @objc inference
根据提案中的描述,您的第二个代码片段也需要@objc
。
事实上,与 Xcode 9 beta2 捆绑在一起的 Swift 4 编译器会为使用 #selector(tapped)
的行生成此错误:
error: argument of '#selector' refers to instance method 'tapped()' that is not exposed to Objective-C
note: add '@objc' to expose this instance method to Objective-C
也许你的第二个有点太老了,无法与 Swift 4 一起使用。你最好考虑通过选择器调用的所有方法都需要 @objc
属性。强>
关于ios - 选择器与 Action Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44836777/