我正在尝试传递带有 NSTimer 用户信息的 UIButton。我已经阅读了 NSTimers 上关于 stackoverflow 的所有帖子。我已经很接近了,但还不能完全到达那里。这篇文章有帮助
func timeToRun(ButonToEnable:UIButton) {
var tempButton = ButonToEnable
timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("setRotateToFalse"), userInfo: ["theButton" :tempButton], repeats: false)
}
定时器运行的函数
func setRotateToFalse() {
println( timer.userInfo )// just see whats happening
rotate = false
let userInfo = timer.userInfo as Dictionary<String, AnyObject>
var tempbutton:UIButton = (userInfo["theButton"] as UIButton)
tempbutton.enabled = true
timer.invalidate()
}
最佳答案
我知道你已经设法解决了这个问题,但我想我会给你更多关于使用 NSTimer
的信息。访问定时器对象和用户信息的正确方法是像下面这样使用它。初始化计时器时,您可以像这样创建它:
swift 2.x
NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("setRotateToFalse:"), userInfo: ["theButton" :tempButton], repeats: false)
swift 3.x<
Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.setRotateToFalse), userInfo: ["theButton" :tempButton], repeats: false)
然后回调看起来像这样:
func setRotateToFalse(timer:NSTimer) {
rotate = false
let userInfo = timer.userInfo as Dictionary<String, AnyObject>
var tempbutton:UIButton = (userInfo["theButton"] as UIButton)
tempbutton.enabled = true
timer.invalidate()
}
因此,您不需要保留对计时器的引用,并尽可能避免经常使用讨厌的全局变量。如果你的类不是从 NSObject
继承的,你可能会很快遇到问题,它说没有定义回调,但这可以通过添加 @objc
轻松解决函数定义的开头。
关于快速 NSTimer 用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29140214/