我试图用NSTimer的用户信息传递一个UIButton。我读过NSTimers上每一篇关于堆栈溢出的文章。我离得很近,但到不了那里。这篇文章很有帮助
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()
}发布于 2015-03-20 19:14:26
我知道你已经解决了这个问题,但是我想我会给你一些关于使用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可以很容易地修复这个问题。
发布于 2018-01-10 17:50:36
macOS 10.12+和iOS 10.0+引入了一种基于块的Timer API,这是一种更方便的方法。
func timeToRun(buttonToEnable: UIButton) {
timer = Timer.scheduledTimer(withTimeInterval:4, repeats: false) { timer in
buttonToEnable.enabled = true
}
}一枪定时器在发射后会自动失效。
使用GCD (DispatchQueue.main.asyncAfter)也是一种类似的方便的一次性计时器方式。
func timeToRun(buttonToEnable: UIButton) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4)) {
buttonToEnable.enabled = true
}
}发布于 2015-03-19 08:48:40
我只是想在我发帖之前读到这篇文章的时候把它贴出来。我注意到我在userinfo之前就有timer.invalidate()了,这就是为什么它不能工作的原因。我会把它发出去,因为它可能对别人有帮助。
func setRotateToFalse(timer:NSTimer) {
rotate = false
timer.invalidate()
let userInfo = timer.userInfo as Dictionary<String, AnyObject>
var tempbutton:UIButton = (userInfo["theButton"] as UIButton)
tempbutton.enabled = true
}https://stackoverflow.com/questions/29140214
复制相似问题