快速 NSTimer 用户信息

标签 swift nstimer userinfo

我正在尝试传递带有 NSTimer 用户信息的 UIButton。我已经阅读了 NSTimers 上关于 stackoverflow 的所有帖子。我已经很接近了,但还不能完全到达那里。这篇文章有帮助

Swift NSTimer retrieving userInfo as 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()    
}

最佳答案

我知道你已经设法解决了这个问题,但我想我会给你更多关于使用 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/

相关文章:

ios - 嵌套 Collection View Swift 4.2

ios - NSTimer "target": How to reference a method of a class?

ios - 随时恢复 UILocalNotification 或远程推送通知

ios - 如何在 Swift 中获取图像文件大小?

swift - 如何在 IBM Cloud Application Tools 中创建的 XCode 中打开项目?

ios - 如何快速重新启动计时器

Django:如何在 View 请求之外获取登录用户?

api - Auth0调用userinfo的正确方法

swift - 用于检查 Optional 在 Swift 中是否为 nil 的一行代码

ios - Swift 对包含计时器的方法进行单元测试