谁能告诉我为什么这段代码给出错误消息“'#selector' 的参数不引用'@objc' 方法、属性或初始化程序”?
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(until: 3)), userInfo: nil, repeats: true)
函数如下:
func updateTimer(until endTime: Int) {
counter -= 1
timeLabel.text = String(counter)
if counter == endTime {
step += 1
}
}
我尝试过的:
1.在函数前添加@objc。
最佳答案
目标/操作方法的选择器必须在没有参数的情况下声明,或者有一个参数传递受影响的对象。
在 Timer
的情况下,使用 userInfo
参数传递数据。
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(_:)), userInfo: 3, repeats: true)
func updateTimer(_ timer: Timer) {
let endTime = timer.userInfo as! Int
counter -= 1
timeLabel.text = String(counter)
if counter == endTime {
step += 1
}
}
如果封闭类不继承 NSObject
形式,则必须将 @objc
属性添加到操作方法。
关于swift - '#selector' 的参数不引用 '@objc' 方法、属性或初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493778/