15

我正在尝试使用 NSTimer 的用户信息传递 UIButton。我已经阅读了 NSTimers 上关于 stackoverflow 的每一篇文章。我已经非常接近了,但无法完全到达那里。这篇文章有帮助

Swift NSTimer 检索 userInfo 作为 CGPoint

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()    
}
4

3 回答 3

32

我意识到你已经设法解决了这个问题,但我想我会给你更多关于使用NSTimer. 访问计时器对象和用户信息的正确方法是使用它,如下所示。初始化计时器时,您可以像这样创建它:

斯威夫特 2.x

NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("setRotateToFalse:"), userInfo: ["theButton" :tempButton], repeats: false)

斯威夫特 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()    
}

因此,您不需要保留对计时器的引用,并尽可能避免经常使用讨厌的全局变量。如果您的类没有从它说没有定义回调的地方继承,您可能会在 swift 中遇到问题,NSObject但这可以通过@objc在函数定义的开头添加来轻松解决。

于 2015-03-20T19:14:26.080 回答
1

我只是要发布这个,因为我在发布之前阅读了它。我注意到我timer.invalidate()之前有 userinfo 所以这就是它不起作用的原因。我会发布它,因为它可能会帮助其他人。

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
}
于 2015-03-19T08:48:40.600 回答
1

macOS 10.12+ 和 iOS 10.0+ 引入了基于块的 API,Timer这是一种更方便的方式

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
    }
}
于 2018-01-10T17:50:36.643 回答