2015-11-19 63 views
1

我正在使用UITableViewAutomaticDimension來讓我的TableViewCells自動調整內容大小。如果第一個單元格中有多行文本,它將採用正確的高度,但只顯示第一行內容,直到我向下滾動並備份。UILabel沒有立即獲取內容

該標籤在故事板中配置有:

初始加載:

滾動後:

ViewDidAppear:

override func viewDidAppear(animated: Bool) { 
    super.viewDidAppear(animated) 

    self.tableView!.estimatedRowHeight = 250 
    self.tableView!.rowHeight = UITableViewAutomaticDimension 
    ProgressHUD.show("Loading...", interaction: false) 
    let API = postAPI() 
    API.getNew() { 
     (result: [Post]?) in 
     ProgressHUD.dismiss() 
     if let ps = result { 
      if self.posts.count != ps.count { 
       self.posts.removeAll() 
       self.posts.appendContentsOf(ps) 
       self.tableView.reloadData() 
      } 
     } else { 
      ProgressHUD.showError("There was a problem getting new posts") 
     } 
    } 
} 

的cellForRowAtIndexPath:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("OMCFeedCell", forIndexPath: indexPath) as! OMCFeedTableViewCell 
    let p = posts[indexPath.row] 

    cell.selectionStyle = .None 
    let data = p.content!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 
    let content = try! JSON(NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) 

    if let image = content["image"].string { 
     let uploads = uploadAPI() 
     uploads.tryGetImage(image) { 
      (result: UIImage?) in 

      if let i = result { 
       cell.postImage.contentMode = .ScaleAspectFit 
       cell.postImage.image = i 
      } 
     } 
    } 

    cell.postText.text = "" 
    if let text = content["text"].string { 
     cell.postText.text = text 
    } 

    return cell 
} 

投票欄上的約束:

+0

你可以在你的'cellForRowAtIndexPath'中顯示代碼嗎?在Storyboard中如何配置標籤? – Paulw11

+0

@ Paulw11我添加了相關的代碼和配置選項 –

+0

認爲他們想看到約束。 – beyowulf

回答

0

您將需要確保您的UI更新發生在主線程。我懷疑你的API.getNew()調用似乎是異步的,可能該塊在輔助線程中被回調? (我只是猜測它)。確保UI更新在主線程中發生。做此更改代碼 -

API.getNew() { 
    (result: [Post]?) in 
    //Ensure to run UI updates in main thread. The ProgressHUD.dismiss(), 
    //self.tableView.reloadData() must be run in main thread.. 
    dispatch_async(dispatch_get_main_queue(),{ 
     if let ps = result { 
      ProgressHUD.dismiss() 
      if self.posts.count != ps.count { 
       self.posts.removeAll() 
       self.posts.appendContentsOf(ps) 
       self.tableView.reloadData() 
      } 
     } else { 
      ProgressHUD.showError("There was a problem getting new posts") 
     } 
    }) 
} 

同樣看出來這種圖紋在你的代碼,並確保您不會從輔助線程運行的UI更新。

+0

修復了模擬器中的代碼,但不是在硬件iPhone上。奇怪!請注意,我的SIM卡在iOS 9上,我的iPhone在iOS 8上。 –

+0

我最終找到了[此鏈接](http://useyourloaf.com/blog/self-sizing-table-view-cells。html#comment-1992126862),它告訴我在從cellForRowAtIndexPath返回之前添加cell.layoutIfNeeded()。終於修復了iOS 8! –