ios 选择器与动作 Swift 4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44836777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:17:10  来源:igfitidea点击:

Selector vs Action Swift 4

iosswiftselectorswift4

提问by user2511882

New to Swift. I have two snippets below:

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"]!)")

}

and finally

最后

let x:UITapGestureRecognizer = UITapGestureRecognizer(target: self, 
    action: #selector(tapped))

self.addGestureRecognizer(x)

func tapped(){
    print("tapped")

    self.delegate!.theViewTapped()

}

Why is it that for the notificationCenter? I am supposed to provide the @objctag for the selectorparameter but not for the UITapGestureRecognizeraction parameter?

为什么是这样notificationCenter?我应该@objcselector参数提供标签而不是为UITapGestureRecognizer动作参数提供标签?

What exactly is the difference between Selectorand Action inSwift?

SelectorAction inSwift到底有什么区别?

回答by OOPer

Check this proposal for Swift 4: SE-0160 Limiting @objc inference

检查 Swift 4 的这个提议: SE-0160 限制 @objc 推理

According to the description in the proposal, your second code snippet also needs @objc.

根据提案中的描述,您的第二个代码段也需要@objc.

In fact, Swift 4 compiler bundled with Xcode 9 beta2 generates this error for the line using #selector(tapped):

实际上,与 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

错误:“#selector”的参数引用了未暴露给 Objective-C 的实例方法“tapped()”

注意:添加“@objc”以将此实例方法公开给Objective-C

Maybe your second is a little bit too old to use with Swift 4. You better think all methods invoked through selector need @objcattribute.

也许你的第二个有点太老了,无法与 Swift 4 一起使用。你最好认为所有通过选择器调用的方法都需要@objc属性。