简体   繁体   中英

How can I get my Swift class to update the label in my viewcontroller in real time?

I'm using Swift 2+ and doing a stopwatch/timer.

Basically, I've got a class, StopWatch2, that I can call from my ViewController.

I can make the timer within the class start, run, stop, and reset.

I can also make it update the label in my ViewController, but only for 'now.' For example, if I start the timer, the label will say 7:59. I can see in my print log that the timer is counting down, but it's not updating the label. If I click 'Stop,' the label will update with the current time.

All the code is here - https://github.com/markie1313/Debate-Timer . If I need to post code samples, I'd be glad to.

What to do?

mark

UPDATE:

Sorry for the delay. Here's the code I'm using for the ViewController

class ViewController2AC: UIViewController { var newTimer = StopWatch2()

@IBOutlet var timerText: UILabel!
@IBOutlet var startStopButton: UIButton!

@IBAction func startStopTimer(sender: AnyObject) {
    timerText.text = "8:00"
    newTimer.startStop()
    timerText.text = newTimer.stopWatchString

}

override func viewDidLoad() {
    super.viewDidLoad()
    newTimer.minutes = 7
    newTimer.seconds = 60
}    

}

Here are the functions being called:

func startStop() {

    if startStopwatch == true {
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateStopwatch"), userInfo: nil, repeats: true)
        startStopwatch = false
        startStopButtonExt = "Stop"
    } else {
        timer.invalidate()
        startStopwatch = true
        startStopButtonExt = "Start"
    }
}

func updateStopwatch() -> String {
    seconds -= 1
    if seconds == 0 && minutes == 0 {
        timer.invalidate()
        labelText = "0:00"
        return self.labelText
    }
    if seconds == 0 {
        labelText = "\(minutes):00"
        print(labelText)
        minutes -= 1
        seconds = 60
    }
    var secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
    var minutesString = minutes > 9 ? "\(minutes)" : "\(minutes)"
    if seconds == 60 {
        secondsString = "00"
        minutesString = "\(minutes + 1)"
    }
    stopWatchString = "\(minutesString):\(secondsString)"
    labelText = stopWatchString
    print("\(stopWatchString) test")
    return self.stopWatchString
}

每次您view.setNeedsDisplay操作主线程上的UI标签时,都必须调用view.setNeedsDisplay

You have to update label text in the end of updateStopwatch method:

timerText.text = labelText

Also I suggest you to use format string instead of number > 9

String(format: "%02d", myInt)

This will apply leading zeros to your number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM