update text field ui in swift ios

天大地大妈咪最大 提交于 2019-12-18 05:12:31

问题


i meet a question when i'm using swift of ios SDK 8

I used a callback to fetch data background and when data fetched, i want to set a text field value and update screen.

here is my code:

@IBOutlet var txtTest: UITextField!

@IBAction func login() {
    let username = "aaa";
    let password = "bbb";
    var res = ServiceClient.login(username, password: password){
        (res:String, error:String?) -> Void in if(error == nil){
            self.txtTest.text = res;
        }
    }
}

Run this code and the data is correctly fetched and the txtTest did not updated, but when i tap txtTest, the value will be shown. So is there any way to force update UI? or send a message to UI thread?


回答1:


Same issue that everyone is having when wanting to do UI updates in Swift: do not ever update the UI in any secondary thread. And that means anything with closures. Since Swift is using closures so much, that issue is being seen a lot more but it isn't new.

See Swift Update Label (with HTML content) takes 1min for the correct way of doing things.




回答2:


UIKit is not thread-safe and should only be updated from the main thread. Downloads are done on the background thread, and you cannot update UI from there. Try:

For swift 3 and swift 4

DispatchQueue.main.async {
    self.txtTest.text = "Your text"
}

Related duplicate question but with specific answer

iOS label does not update text with function in Swift



来源:https://stackoverflow.com/questions/25603568/update-text-field-ui-in-swift-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!