简体   繁体   中英

How to change a label text during a for loop in IOS swift4?

I want to change/reload my label on activity indicator while I am running the for loop. But I am unable to change my label text.

for i in 0..<(tempAry.count)
{
  self.tempLbl.text = "\(i) Task Completed"
}

You can't visible label text from for loop every time, You will visible only last index label.

Time complexity of this for loop is O(1) so execution time of whole for loop is in milliseconds.

So better way to use the Timer to show the text on the label.

Define globally.

var count = 0
var timer: Timer?

In viewDidLoad method add timer.

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

Outside ViewDidLoad method put below method.

@objc func updating() {
        if count >= 100 - 1{
            timer?.invalidate()
            timer = nil
            return
        }

        count += 1
        self.title = "\(count) Task Completed"
    }

Actually previously added answer is working fine.

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