【问题标题】:Swift: Value does not load to text fieldSwift:值不会加载到文本字段
【发布时间】:2015-07-23 18:40:53
【问题描述】:

当屏幕加载时,它会从 REST 调用中获取响应,然后更新 UI。
Flow 工作正常,但不知何故它没有更新textfield 的值。适用于标签。

标签已更新,文本字段未更新。

override func viewDidLoad() {
        super.viewDidLoad()
        getContactInfo(id) //Rest call
}

其余部分调用

let task = session.dataTaskWithRequest(request) { (data, responseData, error) -> Void in
                if let response = responseData as? NSHTTPURLResponse {
                    self.statusCode = response.statusCode
                    print("Response code: \(response)")
                }

                do {
                    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary {
                        //json parsing
                    }

                } catch {
                    print(error)

                }

                if(self.statusCode != 200) {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print("Error could not parse JSON: '\(jsonStr)'")
                }
                else {
                    let name = self.contact?.firstName
                    print("Everything Looks good: \(name!)")
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.updateUI()
                    })
                }
            }
            task?.resume()
      //  }

    }

更新用户界面

private func updateUI() {
        print("Refresh UI1")
        if contact != nil {
            print("Refresh UI2")
            self.firstName.text = (contact?.firstName)!
            self.name.text = (contact?.firstName)!
        }

    }

控制台输出

Everything Looks good: Derp
Refresh UI1
Refresh UI2

注意:这样做是否正确?(我是 iOS 开发新手)

【问题讨论】:

  • 您能否也发布控制台输出,以检查 Refresh UI2 行是否执行?
  • 是的,查看 contact 和 self.contact 的声明/值可能也会有所帮助。

标签: ios swift ios8


【解决方案1】:

如何在异步线程上更新 UI 的正确方法如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        // Update UI
    })
})

希望对你有帮助!

【讨论】:

  • 你的意思是else { let name = self.contact?.firstName print("Everything Looks good: \(name!)") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.updateUI() }) }) }
【解决方案2】:

试试这个,

private func updateUI() {

 print("Refresh UI1")
        if contact != nil {
            print("Refresh UI2")
             dispatch_async(dispatch_get_main_queue()) {
              self.firstName.text = (contact?.firstName)!
              self.name.text = (contact?.firstName)!
             }
           }
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多