NSTimer/Timer 持续时间和 UI 更新

NSTimer/Timer duration and UI update

可能是一个简单的问题,但是,我似乎无法构思出一种优雅的方法。

我想设计一个简单的应用程序,允许将计时器设置为持续时间(例如 1 分钟),在该持续时间之后计时器应该到期, 持续时间计时器应每秒更新 UI。

因此,如果计时器设置为一分钟,计时器应该启动,每秒更新 UI(通过调用方法),然后在 1 分钟后最终失效。

我的难题是,我可以设置一个 scheduledTimerWithInterval,它在定时器间隔上调用一个方法。如果我将这 1 分钟设为 1 分钟,我可以在一分钟后调用一个方法使计时器无效,但似乎没有一种机制可以在 这一分钟.[=13= 期间执行调用]

你能给我一些指导吗?

Swift 3.x code

制作两个全局变量

var seconds = 1
var secondTimer:Timer?

然后做这两个函数

// for setup of timer and variable
func setTimer() {
    seconds = 1

    secondTimer?.invalidate()
    secondTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateUI), userInfo: nil, repeats: true)
}

//method to update your UI
func updateUI() {
    //update your UI here

    //also update your seconds variable value by 1
    seconds += 1
    if seconds == 60 {
        secondTimer?.invalidate()
        secondTimer = nil
    }
    print(seconds)
}

终于可以随时随地调用setTimer()

我会做这样的事情:

1:声明一个timer和一个计数器:

var timer = Timer()
var counter = 0

2:创建一个新的函数,例如startEverySecond,以一秒为间隔启动定时器,该函数在60秒后调用,将调用1分钟,然后失效:

func startEverySecond() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(everySecond), userInfo: nil, repeats: true)
}

func everySecond(){
    if counter == 60{
        timer.invalidate()
    }
    counter = counter + 1
    print("Second")
}

3:处理定时器的启停:

// Start with 60 second interval
timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(startEverySecond), userInfo: nil, repeats: false)

// Stop
timer.invalidate()

所以基本上,当您启动计时器时,它会以 60 秒开始计时,完成后它将调用函数 startEverySecond,这将更改计时器以每隔 60 秒调用一次函数 everySecond秒 1 分钟。要停止计时器,只需调用 timer.invalidate()