3

我希望父母ViewController处理由其中一个孩子生成的 Target-Actions ViewControllers

根据 Apple 文档,这应该可以通过设置并遵循响应者链target来实现。nil

如果您为目标对象指定 nil,则控件会在响应程序链中搜索定义指定操作方法的对象。https://developer.apple.com/documentation/uikit/uicontrol

但是如何在targetis时编写动作方法签名nil

通常,您将函数名称附在#selector()其中,让您在编译时检查是否存在具有该签名的方法。像这样:

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

    func buttonPressed(sender: UIButton) { }

}

但是因为编译targetnil因为找不到它而抱怨:

// ! 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)
4

2 回答 2

3

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

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

仅供参考,我从 2016 年 1 月的这篇不错的博客文章中得到了答案,下载了源文件,并让 XCode 将其转换为 Swift 3 语法:-)

于 2017-07-21T17:50:28.637 回答
0

这对我有用,请注意双括号以避免警告: NSApp.sendAction(Selector(("enterActivationNumber:")), to: nil, from: sender)

于 2020-01-29T11:28:23.737 回答