Clarence Clarence - 5 months ago 18
iOS Question

Swift 3 Counting up timer failed to show the updated number in UILabel

I have the following count up timer, but after i run the program, the UILable generate from 0 then to (). But the counter number is correct because i can see the printing log is correct.
May I know what's going wrong with the code.`

@IBOutlet weak var labelForBinaryCount: UILabel!

var timer = Timer()
var counter = 0


@IBAction func start() {

timer = Timer.scheduledTimer(timeInterval: 1, target:self, selector: #selector(Resting.updateCounter), userInfo: nil, repeats: true)

}

override func viewDidLoad() {
super.viewDidLoad()
labelForBinaryCount.text = String(counter)

}

func updateCounter() {
labelForBinaryCount.text = String(describing: counter += 1)
print(counter)
}

@IBAction func pauseButton(sender: AnyObject) {
timer.invalidate()
}
@IBAction func clearButton(sender: AnyObject) {
timer.invalidate()
counter = 0
labelForBinaryCount.text = String(counter)
}`

Answer Source

Try this:

func updateCounter() {
    counter += 1
    labelForBinaryCount.text = String(counter)
    print(counter)
}

I think you understand. ;)