代码之家  ›  专栏  ›  技术社区  ›  MH175

addTarget:action:forControlEvents:target为nil时的选择器语法?

  •  3
  • MH175  · 技术社区  · 8 年前

    我想要一个家长 ViewController 处理由其子对象之一生成的目标操作 ViewControllers

    根据苹果文档,这应该可以通过设置 target nil 并遵循响应链。

    如果为目标对象指定nil,则控件将搜索 定义指定动作的对象的响应器链 https://developer.apple.com/documentation/uikit/uicontrol

    但是,当

    通常将函数名括在 #selector() 这将在编译时检查是否存在具有该签名的方法。像这样:

    class MyViewController: UIViewController {
        override func viewDidLoad() {
             self.button.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchDown)
        }
    
        func buttonPressed(sender: UIButton) { }
    
    }
    

    但是自从 目标 编译器抱怨,因为它找不到它:

    // ! Use of unresolved identifier "buttonPressed(sender:)"
    button.addTarget(nil, action: #selector(buttonPressed(sender:)), for: .touchDown)
    

    我尝试使用字符串初始化选择器,但编译器也有问题。

        // ! String literal is not a valid Objective-C selector
        button.addTarget(nil, action: Selector("buttonPressed(sender:)"), for: .touchDown)
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   MH175    8 年前

    解决方案是以定义类的名称作为前缀。

        button.addTarget(nil, action: #selector(MyViewController.buttonPressed(sender:)), for: .touchDown)
    

    告诉你,我已经搞定了 this nice blog post from Jan 2016 ,下载源文件,并让XCode将其转换为Swift 3语法:-)

        2
  •  0
  •   Oleksii Nezhyborets    6 年前

    NSApp.sendAction(Selector(("enterActivationNumber:")), to: nil, from: sender)