Swift NSTimer 动态改变间隔 [英] Swift NSTimer dynamically changing interval

查看:71
本文介绍了Swift NSTimer 动态改变间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改 NSTimer 上的时间间隔?

How can I change the time interval on an NSTimer?

var difficulty: Double = 1.0

override func viewDidLoad() {
    super.viewDidLoad()

    _ = NSTimer.scheduledTimerWithTimeInterval(difficulty, target: self, selector: #selector(hideAllBtns), userInfo: nil, repeats: true)

}

我运行了一个 switch 语句,每次都从 hideallbuttons 调用,然后更新难度.

I run a switch statement which gets called each time from hideallbuttons and that then updates the difficulty.

func getDifficulty (score : Double) -> Double {

    switch score {

    case 0...100: return(1.0)
    case 100...200: return (0.8)
    case 200...300: return (0.5)
    case 300...400: return (0.2)
    default: return (1.0)

    }
}

然而,NSTimer 继续在 1.0 秒触发,我认为它会在第一次运行时创建一个副本并坚持该值,我试图在计时器调用中创建一个变量,但没有用.

However NSTimer continues to fire at 1.0s I presume it creates a copy upon first run and sticks to that value, I have tried to create a variable in the timer call but that doesn't work.

有没有一种简单的方法可以动态调整定时器触发的速率?

Is there a simple way to adjust the rate dynamically at which the timer fires?

这只是一个练习项目,因为我仍在学习,所以我知道可能有更好的方法来构建我正在尝试做的事情.我认为动态调整计时器对将来使用很有用.

This is just a practice project as I am still learning, so I understand there is probably a much better way to structure what I am trying to do. I think a dynamically adjusting timer would be useful for future use.

推荐答案

你不能,一旦你触发定时器,它就会运行.

You can't, once you fire the timer, it runs.

我不确定您到底需要什么,但您有两个选择:

I am not sure what exactly you need but you have two options:

  1. 使计时器失效,并以新的时间间隔触发一个新的计时器,您甚至可以在类中声明计时器,并只需覆盖该值(在您失效后).

  1. Invalidate the timer, and fire a new one with new time interval, you can even declare the timer in the class, and just override the value (after you invalidate).

将重复值设置为 false 并每次触发新的计时器.

Set the repeat value to false and fire new timer every time.

看看这个例子:

class ViewController: UIViewController {
    var difficulty: Double = 1.0
    var timer = NSTimer()

    override func viewDidLoad() {
        activateTimer()
    }

    func activateTimer(){
       timer = NSTimer.scheduledTimerWithTimeInterval(difficulty, target: self, selector: Selector(self.timerMethod()), userInfo: nil, repeats: true)
    }

    func timerMethod() {
        print("Timer method called")
    }

    func endTimer() {
        timer.invalidate()
    }

    func increaseDifficulty() {
      difficulty = 2.0
      endTimer()
      activateTimer()
    }

}

这篇关于Swift NSTimer 动态改变间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆