我试图在我的应用程序模型中保留一个 NSTimer 并更新我的 View Controller 文件中的时间。为此,我创建了这两种方法:
func startTimer(labelToUpdate : UILabel) {
timerGoing = true
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "decTimeByOne:labelToUpdate:", userInfo: labelToUpdate, repeats: true)
}
func decTimeByOne(labelToUpdate : UILabel) {
if timerGoing {
if decreasingTime > 0 {
decreasingTime--;
labelToUpdate.text = "\(decreasingTime)"
}
else {
timerGoing = false
timer.invalidate()
}
}
}
我在控制台中收到运行时异常(我相信)有一个“无法识别的选择器”。在做了一些研究之后,我的印象是这是 Swift 中用于在选择器中调用多个参数方法的语法:selector: "methodName:argumentName:", userInfo: argumentPassedIn,
最后,我想保留一个与我的模型对象相关联的计时器,并且只更新该时间并显示在我的应用程序 View 中。这是解决此问题的正确方法吗?
最佳答案
I was under the impression that this was the syntax used in Swift to call multiple argument methods within selectors: `selector: "methodName:argumentName:"
在某种程度上这是对的,但它并不能免除您的责任,如果您要使用 NSTimer,请阅读 NSTimer 上的文档。特别是,它不会改变 NSTimer 调用的选择器不由您决定的事实。它只能是 methodName:
的形式,因为它只需要一个参数——计时器(不是标签或其他任何东西)。正如您已经被告知的那样,如果您有其他信息要传递,请将其附加到将传递的计时器。
现在,此外,您还在如何陈述您的方法名称方面是错误的。声明为 func decTimeByOne(labelToUpdate : UILabel
的方法的选择器是 decTimeByOne:
。同样,这不取决于你;你必须知道如何制作的规则一个选择器。
关于ios - Swift:使用带有多个参数的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756914/