【问题标题】:Selector vs Action Swift 4选择器与动作 Swift 4
【发布时间】:2017-06-30 00:07:35
【问题描述】:

Swift 新手。我在下面有两个 sn-ps:

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?我应该为selector 参数提供@objc 标签,但不为UITapGestureRecognizer 操作参数提供标签?

SelectorAction in Swift 到底有什么区别?

【问题讨论】:

标签: ios swift selector swift4


【解决方案1】:

查看 Swift 4 的提案: SE-0160 Limiting @objc inference

根据提案中的描述,你的第二个代码sn-p也需要@objc

事实上,与 Xcode 9 beta2 捆绑在一起的 Swift 4 编译器会为使用 #selector(tapped) 的行生成此错误:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2018-09-29
    • 1970-01-01
    相关资源
    最近更新 更多