iOS标签无法使用Swift中的功能更新文本 [英] iOS label does not update text with function in Swift
问题描述
这个看似简单的问题使我发疯……我正在玩SwiftyJSON来获取远程数据,这是我在Swift中的ViewController类的摘录:
This seemingly simple issue is driving me crazy... I am playing around with SwiftyJSON to grab remote data and here is a snippet from my ViewController class in Swift:
override func viewDidLoad() {
super.viewDidLoad()
self.statusLabel.text = "welcome"
RemoteDataManager.getStatusUpdateFromURL { (statusData) -> Void in
let json = JSON(data: statusData)
self.statusLabel.text = "this does not work"
self.statusLabel.text = self.getMostRecentStatusUpdate(json) // also does not work
}
}
statusLabel文本设置为欢迎",但此后不会更改.有趣的是,我放在func getMostRecentStatusUpdate(_:)
和println()
中的任何内容都正确地打印到了控制台,即使它来自远程json源(即我知道此功能也可以).我的问题是我无法将文本打印到UILabel而不是控制台上.我没有收到任何错误消息.
The statusLabel text is set to "welcome" but does not change afterwards. Funny though, anything I put inside func getMostRecentStatusUpdate(_:)
with println()
is printed to the console correctly, even if it comes from the remote json source (i.e. I know that this function works). My problem is that I cannot get the text printed to a UILabel instead of the console. I do not get any error messages.
我还不太熟悉像MyClass.myMethod { (myData) -> Void in .... }
这样的Swift函数,我不明白这里出了什么问题.有什么想法吗?
I am not yet really familiar with the sort of Swift function like MyClass.myMethod { (myData) -> Void in .... }
and I don't understand what's going wrong here. Any ideas?
推荐答案
UIKit
不是线程安全的,只能从主线程进行更新.下载是在后台线程上完成的,您不能从那里更新UI.试试:
UIKit
is not thread safe and should only be updated from the main thread. Downloads are done on background thread, and you cannot update UI from there. Try:
override func viewDidLoad() {
super.viewDidLoad()
self.statusLabel.text = "welcome"
RemoteDataManager.getStatusUpdateFromURL { (statusData) -> Void in
let json = JSON(data: statusData)
dispatch_async(dispatch_get_main_queue()) {
self.statusLabel.text = "this does not work"
self.statusLabel.text = self.getMostRecentStatusUpdate(json) // also does not work
}
}
}
这篇关于iOS标签无法使用Swift中的功能更新文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!