我正试图在Swift中创建一个Swift,但我遇到了一些麻烦。
NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)test()是同一个类中的函数。
我在编辑器中发现了一个错误:
无法找到接受所提供的参数的“init”重载
当我将selector: test()更改为selector: nil时,错误将消失。
我试过:
selector: test()selector: testselector: Selector(test())但什么都没用,我在推荐信中找不到解决办法。
发布于 2014-06-03 05:31:39
下面是一个关于如何在Swift上使用Selector类的快速示例:
override func viewDidLoad() {
super.viewDidLoad()
var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
self.navigationItem.rightBarButtonItem = rightButton
}
func method() {
// Something cool here
}注意,如果作为字符串传递的方法不起作用,它将在运行时失败,而不是编译时,并使应用程序崩溃。注意
发布于 2014-06-24 15:23:39
另外,如果您的(Swift)类不是从Objective类降下来的,那么在目标方法名称字符串的末尾必须有一个冒号,并且您必须在目标方法中使用@objc属性。
var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
@objc func method() {
// Something cool here
} 否则,您将在运行时得到“未识别的选择器”错误。
发布于 2016-04-06 16:06:21
Swift 2.2+和Swift 3更新
使用新的#selector表达式,消除了使用字符串文字的需要,从而减少了使用错误的可能性。供参考:
Selector("keyboardDidHide:")变成了
#selector(keyboardDidHide(_:))另见:快速演进方案
注(SWIFT4.0):
如果使用#selector,则需要将函数标记为@objc
示例:
@objc func something(_ sender: UIButton)
https://stackoverflow.com/questions/24007650
复制相似问题