swift - '#selector' 的参数不引用 '@objc' 方法、属性或初始值设定项

标签 swift swift3 selector

谁能告诉我为什么这段代码给出错误消息“'#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/

相关文章:

css - 有什么方法可以仅使用 CSS 将元素的索引(子编号)作为文本插入到元素中?

regex - 解码正则表达式以了解它是否仅允许数字

ios - 即使在添加 subview 后, View 层次结构也未准备好约束

ios - 如何在另一个自定义表格 View 中快速创建自定义表格 View

ios - 使用按钮添加和删除 subview

jquery - 如何选择具有特定 id 的父级的图像元素?

c# - WPF 选择器——如何确保它只允许单选而不允许多选?

ios - 为非续订订阅恢复未处理的 SKPaymentTransaction

ios - NSUserdefault 不适用于 PFObject

ios - swift 3 : Resizing UICollectionViewCell programmatically causes cells to overlap