在滚动视图上创建计时器

时间:2015-07-30 13:51:26

标签: ios swift timer scrollview

如何在滚动视图上创建计时器功能。

我已经实现了一个正常工作的计时器功能,但由于scrollView的性质,每次刷页时视图控制器都会加载。计时器重置。

如何从scrollView的每个页面存储计时器的值,以便它不会重置?

以下是我的计时器功能:

override func viewDidAppear(animated: Bool) {

    // Start Timer Variables
    startGame()
    timerButtonStart()

}

计时器功能

// Mark : Timer Functions

func startGame() {

    let aSelector : Selector = "updateTime"
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
    startTime = NSDate.timeIntervalSinceReferenceDate()

}

@IBAction func pauseTimer(sender: AnyObject) {

    if timerPaused == false {

        elapsedTime += startTimeDate.timeIntervalSinceNow
        timer.invalidate()
        timerPaused = true

    } else {
        let aSelector : Selector = "updateTime"
        timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
        startTimeDate = NSDate()
        startTime = NSDate.timeIntervalSinceReferenceDate() + elapsedTime
        timerPaused = false
    }
}

func updateTime() {

    var currentTime = NSDate.timeIntervalSinceReferenceDate()

    //Find the difference between current time and start time.
    var elapsedTime: NSTimeInterval = currentTime - startTime

    //calculate the minutes in elapsed time.
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (NSTimeInterval(minutes) * 60)

    //calculate the seconds in elapsed time.
    let seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)

    //find out the fraction of milliseconds to be displayed.
    let fraction = UInt8(elapsedTime * 100)

    //add the leading zero for minutes, seconds and millseconds and store them as string constants
    let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
    strMinutesGlobal = strMinutes
    strSecondsGlobal = strSeconds

    //concatenate minuets, seconds and milliseconds as assign it to the UILabel
    timerLabel.text = "\(strMinutesGlobal!):\(strSecondsGlobal!)"
}


func timerButtonStart() {
    var refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "timer") //Use a selector
    navigationItem.leftBarButtonItem = refreshButton

    navigationController!.navigationBar.barTintColor = UIColor.greenColor()
    title = "Search result"
}

2 个答案:

答案 0 :(得分:0)

如果要防止在切换视图控制器时取消分配NSTimer,可以将NSTimer实例存储在单独的单例类而不是视图控制器中。

class MyTimer {
    var sharedInstance = MyTimer()

    var timer: NSTimer?
}

有了这个,您可以像这样访问NSTimer实例:

MyTimer.sharedInstance.timer

答案 1 :(得分:0)

您可以将计时器创建代码更改为

if (timer == nil) {
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
}

并且当您使计时器无效时,您需要将其设置为nil。如果计时器尚不存在,则只会重新创建计时器。