从函数 Xcode/Swift 更改 label.text

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26830751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:08:38  来源:igfitidea点击:

Change label.text from function Xcode/Swift

xcodeswiftios8labelselector

提问by iOsNewbie

I have a timer, which calls a selector. Directly from that function, I want to change the text of a label.

我有一个定时器,它调用一个选择器。直接从该函数中,我想更改标签的文本。

@IBOutlet weak var myLabel: UILabel!

override func viewDidLoad() {
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}

func update () {
self.myLabel.text = "MyNewText"
}

Xcode tells me to use "self", but the label is still not updating! Thanks for your help!

Xcode 告诉我使用“self”,但标签仍未更新!谢谢你的帮助!

回答by zisoft

UI updates must always be done in the main thread, so try this:

UI 更新必须始终在主线程中完成,所以试试这个:

func update () {
    DispatchQueue.main.async {
        self.myLabel.text = "MyNewText"
    }
}