我试图在Swift中创建一个NSTimer,但我遇到了一些麻烦。
NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)
Test()是同一个类中的一个函数。
我在编辑器中得到一个错误:
无法找到一个超载的'init'接受提供的
参数
当我把selector: test()改为selector: nil时,错误就消失了。
我试过了:
选择器:测试()
选择器:测试
选择器:选择器(测试())
但是什么都没用,我在参考文献中找不到解决方案。
Swift 2.2+和Swift 3更新
使用新的#selector表达式,它消除了使用字符串文字的需要,使使用更不容易出错。供参考:
Selector("keyboardDidHide:")
就变成了
#selector(keyboardDidHide(_:))
参见:快速进化提案
注意(Swift 4.0):
如果使用# selector,你需要将函数标记为@objc
例子:
@objc func something(_ sender: UIButton)
同样,如果你的(Swift)类不是来自Objective-C类,那么你必须在目标方法名称字符串的末尾有一个冒号,你必须使用@objc属性与你的目标方法,例如。
var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
@objc func method() {
// Something cool here
}
否则你会在运行时得到一个“unrecognized Selector”错误。
下面是一个关于如何在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
}
请注意,如果作为字符串传递的方法不起作用,它将在运行时失败,而不是在编译时失败,并使应用程序崩溃
如果你想从NSTimer中传递一个参数给函数,那么这里是你的解决方案:
var somethingToPass = "It worked"
let timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "tester:", userInfo: somethingToPass, repeats: false)
func tester(timer: NSTimer)
{
let theStringToPrint = timer.userInfo as String
println(theStringToPrint)
}
在选择器文本(tester:)中包含冒号,参数则放在userInfo中。
你的函数应该以NSTimer作为参数。然后提取userInfo以获得传递的参数。