我建立了一个CountdownTimer,我想将其重构为一个单独的类,以便可以在MainViewController中重用它。我将如何去做?

这是我的代码:

var startTime = NSTimeInterval()
var time:Double = 4
var timer = NSTimer()

/* Outlets */
@IBOutlet weak var timerLabel: UILabel!

 /* CountdownTimer function */
func updateTime() {

    var currentTime = NSDate.timeIntervalSinceReferenceDate()
    var elapsedTime = currentTime - startTime
    var seconds = time - elapsedTime

    if seconds > 0 {
        elapsedTime -= NSTimeInterval(seconds)
        timerLabel.text = "\(Int(seconds))"
    } else {
        timer.invalidate()
        timerLabel.fadeOut()
    }
}

func startTimer () {
    if !timer.valid {
        let aSelector : Selector = "updateTime"
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
        startTime = NSDate.timeIntervalSinceReferenceDate()
    }
}

最佳答案

您可以使用闭包:

class MyTimer: NSObject {

    var startTime: NSTimeInterval! = NSTimeInterval()
    var time: Double! = 4
    var timer: NSTimer! = NSTimer()
    var timerEndedCallback: (() -> Void)!
    var timerInProgressCallback: ((elapsedTime: Double) -> Void)!

    func startTimer(timerEnded: () -> Void, timerInProgress: ((elapsedTime: Double) -> Void)!) {
        if !timer.valid {
            let aSelector : Selector = "updateTime"
            timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
            startTime = NSDate.timeIntervalSinceReferenceDate()
            timerEndedCallback = timerEnded
            timerInProgressCallback = timerInProgress
        }
    }

     func updateTime() {

        var currentTime = NSDate.timeIntervalSinceReferenceDate()
        var elapsedTime = currentTime - startTime
        var seconds = time - elapsedTime

        if seconds > 0 {
            elapsedTime -= NSTimeInterval(seconds)
            timerInProgressCallback(elapsedTime: elapsedTime)
        } else {
            timer.invalidate()
            timerEndedCallback()
        }
    }
}

用法,在您要使用通用计时器的类中:
MyTimer().startTimer({ () -> Void in
    timerLabel.fadeOut()
}, timerInProgress: { (elapsedTime) -> Void in
    timerLabel.text = "\(Int(elapsedTime))"
})

关于ios - 如何在单独的类中的iOS Swift中创建计时器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30661821/

10-14 23:05