2016-07-27 18 views
2

我做了一個UITableView單元,當你點擊它們時展開。它基於以下項目:https://github.com/rushisangani/TableViewCellExpand如何更改UITableViewCell的intrinsicContentSize的工作方式?

基本上,單元格的容器視圖有兩個子視圖,它們充當擴展/收縮狀態的容器 - 「前」和「後」,其中每個都被限制在頂部,單元格主內容視圖的底部,前端和尾部邊緣。爲了使單元格展開或收縮,我只需在前視圖和後視圖的底部約束上切換isActive屬性。這有效,但只有當我點擊時重新加載單元格。如果我只是更改約束,然後嘗試調用invalidateIntrinsicContentSize(),則什麼都不會發生。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
    { 
     // Expand/contract the cell and invalidate size (doesn't work) 
//  let cell = tableView.cellForRow(at: indexPath) as! ExpandingCell 
//  cell.tap() 
//  cell.invalidateIntrinsicContentSize() 

     // Keep track of the selected index and configure the expand/contract state when the cell is remade 
     tableView.deselectRow(at: indexPath, animated: false) 
     expandedIndexPath = indexPath 
     if(!expandedIndexPathArray.contains(indexPath)){ 
      expandedIndexPathArray.append(indexPath) 
     } 
     else{ 
      expandedIndexPathArray = expandedIndexPathArray.filter({$0 != indexPath}) 
     } 

     // Whenever a cell's intrinsicContentSize changes, it must be reloaded 
     tableView.reloadRows(at: [indexPath], with: .none) 
    } 

背後發生了什麼?爲什麼細胞不能重新計算其大小而不重新加載?

回答

2

如果你想承包依據它們的固有內容大小/擴增細胞,你需要做以下3個步驟:

  1. 配置表視圖:

    tableView.rowHeight = UITableViewAutomaticDimension 
    tableView.estimatedRowHeight = 44 
    

    對於靜態表視圖控制器,您將需要執行heightForRowAtIndexPath並返回UITableViewAutomaticDimension

  2. 更新單元格的限制,以反映收縮/擴張狀態

  3. 問表視圖,以反映變化:

    tableView.beginUpdates() 
    tableView.endUpdates() 
    
+0

甜,我喜歡比重裝電池好得多。爲什麼beginUpdates()/ endUpdates()工作,但不invalidateIntrinsicContentSize()? – GoldenJoe

+0

iOS 6中的自動佈局引入了內在內容大小。表視圖類早於此。它也批量變化與自己的動畫等 –

+0

是否有任何體面的文件如何自動佈局的單元格大小的過程工作?我知道如何使用自動佈局實際製作單元格並使其工作,但也很好理解其背後的機制。蘋果公司的文檔在某些方面很糟糕。 – GoldenJoe

相關問題