当计时器结束时如何自动执行Segue?

4
当计时器结束时,我希望自动切换场景。
我在这里构建了一个计时器:
class Timer{
var timer = NSTimer();
// the callback to be invoked everytime the timer 'ticks'
var handler: (Int) -> ();
//the total duration in seconds for which the timer should run to be set by the caller
let duration: Int;
//the amount of time in seconds elapsed so far
var elapsedTime: Int = 0;
var targetController = WaitingRoomController.self


/**
:param: an integer duration specifying the total time in seconds for which the timer should run repeatedly
:param: handler is reference to a function that takes an Integer argument representing the elapsed time allowing the implementor to process elapsed time and returns void
*/
init(duration: Int , handler : (Int) -> ()){
    self.duration = duration;
    self.handler = handler;
}

/**
Schedule the Timer to run every 1 second and invoke a callback method specified by 'selector' in repeating mode
*/
func start(){
    self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onTick", userInfo: nil, repeats: true);
}

/**
invalidate the timer
*/
func stop(){
    println("timer was invaidated from stop()")
    timer.invalidate();
}


/**
Called everytime the timer 'ticks'. Keep track of the total time elapsed and trigger the handler to notify the implementors of the current 'tick'. If the amount of time elapsed is the same as the total duration for the timer was intended to run, stop the timer.
*/


@objc func onTick() {
    //println("onTick")
    //increment the elapsed time by 1 second
    self.elapsedTime++;
    //Notify the implementors of the updated value of elapsed time
    self.handler(elapsedTime);
    //If the amount of elapsed time in seconds is same as the total time in seconds for which this timer was intended to run, stop the timer
    if self.elapsedTime == self.duration {
        self.stop();

    }
}
deinit{
    println("timer was invalidated from deinit()")
    self.timer.invalidate();
}

这是我想要执行segue的视图控制器以及计时器启动的代码:

class WaitingRoomController: UIViewController {

    private func handleSetAction(someTime: String){
       countDownLabel.text = setTime;
       let duration = Utils.getTotalDurationInSeconds(someTime);
       timer = Timer(duration: duration ){
          (elapsedTime: Int) -> () in
             println("handler called")
            let difference = duration - elapsedTime;
            self.countDownLabel.text = Utils.getDurationInMinutesAndSeconds(difference)
       }
       timer.start();
    }
}

我知道自动转场的代码是:
func doSegue(){
    self.performSegueWithIdentifier("asdf", sender: self)
}

但我不知道如何将计时器和这个函数连接在一起。


你能把你的Timer类完整地发布出来吗? - Victor Sigler
2个回答

6

您需要使用闭包来实现您想要的功能,请查看我的Timer类。

import UIKit

class Timer: NSObject {

    var counter: Int = 0
    var timer: NSTimer! = NSTimer()

    var timerEndedCallback: (() -> Void)!
    var timerInProgressCallback: ((elapsedTime: Int) -> Void)!

    func startTimer(duration: Int, timerEnded: () -> Void, timerInProgress: ((elapsedTime: Int) -> Void)!) {

       if !(self.timer?.valid != nil) {
           let aSelector : Selector = "updateTime:"

           timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: duration, repeats: true)

           timerEndedCallback = timerEnded
           timerInProgressCallback = timerInProgress
           counter = 0
       }
    }

    func updateTime(timer: NSTimer) {

       ++self.counter
       let duration = timer.userInfo as! Int

       if (self.counter != duration) {
          timerInProgressCallback(elapsedTime: self.counter)
       } else {
          timer.invalidate()
          timerEndedCallback()
       }
    }
}

然后你可以按照以下方式调用Timer类:

var timer = Timer()

timer.startTimer(5, timerEnded: { () -> Void in
        // Here you call anything you want when the timer finish.
        println("Finished")

        }, timerInProgress: { (elapsedTime) -> Void in
            println("\(Int(elapsedTime))")
})

以上类处理了定时器在已经有效时的使用,并请注意duration参数通过timer参数中的userInfoupdateTime处理程序传递。

希望这可以帮助您。


苹果公司的书中有一章非常好的关于闭包的内容,值得一读。[Closures] (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html) - Victor Sigler
我一直在研究这个,现在终于觉得我理解闭包了!谢谢!我会实现并回来检查的。 - Michael Ninh
开个玩笑,我根本不知道如何为此实现闭包。例如,在“HandleSetAction”中,time = Time(Duration: Duration)。为什么处理程序没有作为参数传递呢? - Michael Ninh
@MichaelNinh 请如果答案解决了您的问题,请将其标记为已接受,以便帮助其他人。 - Victor Sigler

1
将“selector:“On Tick””更改为“selector:@selctor(doSegue)”。您还可以在此处查看更多信息如何使用NSTimer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接