简体   繁体   English

如何在iOS swift4的for循环中更改标签文本?

[英]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. 我要在运行for循环时更改/重新加载活动指示器上的标签。 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. 您不能每次都从for循环中看到标签文本,您只会看到最后一个索引标签。

Time complexity of this for loop is O(1) so execution time of whole for loop is in milliseconds. 此for循环的时间复杂度为O(1),因此整个for循环的执行时间以毫秒为单位。

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. viewDidLoad方法中添加计时器。

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

Outside ViewDidLoad method put below method. 外部ViewDidLoad方法放在下面的方法中。

@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. 实际上以前添加的答案工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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