2016-05-20 97 views
0

這是我viewDidLoad方法 http://i.imgur.com/zTD7wHr.png我的UILabel沒有更新後,我更改文本值

這是我的第一篇文章這麼計算器不會讓我張貼圖片我想我就不得不輟學此鏈接。

基本上,我正在嘗試使用上面的代碼分配位於json的文本:http://catfacts-api.appspot.com/api/facts。我經歷了Xcode中的值,在self.catLabel.text = catFactArray[0] as? String行處有一個斷點,並且catLabel.text字符串具有我想要的值,但標籤不更新。我已經與幾個人去了這個,我真的不知道問題在哪裏,所以任何幫助將不勝感激。

+0

嘗試將標籤更新放在側主隊列中。 – Amit89

+0

如果您將代碼作爲文本粘貼到問題中,您就更有可能得到迴應。很難閱讀屏幕截圖,其他用戶無法複製並編輯它們以測試代碼。 –

回答

1

如果您在後臺執行任何網絡操作並想要更新UI,那麼應該在主線程上完成這些UI更新。

試試吧。

dispatch_async(dispatch_get_main_queue(), { 

     self.catLabel.text = catFactArray[0] as? String 
     self.view.setNeedsDisplay() 
     self.catLabel.setNeedsDisplay() 
}) 
0

你的UI佈局的更新(標籤文本的變化,框架修改..)必須是主線程,在你的代碼進行網絡通話,它在後臺線程可能推出:

let url = NSURL(string: "http://catfacts-api.appspot.com/api/facts") 
let request = NSURLRequest(URL: url!) 
let session = NSURLSession.sharedSession() 
let task = session.dataTaskWithRequest(request, completionHandler : { data, response, error in 
    if let feed = (try? NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)) as! NSDictionary! { 
     if let catFactArray = feed.valueForKeyPath("facts") as! NSArray! { 
      if !NSThread.isMainThread { 
      print("Yes , I'm not in the main thread..") 
      } 
      dispatch_async(dispatch_get_main_queue(), { 
       print("Now I'm in the main thread..") 
       self.catLabel.text = catFactArray[0] as? String 
       self.view.setNeedsDisplay() 
       self.catLabel.setNeedsDisplay() 
       self.catLabel.layoutIfNeeded() 
      } 
     } 
    } 
}) 
task.resume()