0

我有一個UITableView(表1)。在UITableView Cell中我有另一個UITableView(表2)。TableView單元格動態高度

Table 2行的高度是UITableViewAutomaticDimension

我的要求是 - 我想這Table 2不應滾動,並採取充分的高度,每個裏面it.So的行數,按本Table 2的高度,我需要設置Table 1的行高。

我使用表2的contentSize.height,但它不工作。我搜查了很多,但什麼也沒找到。

代碼:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
    { 
     let cell = tableView_First.dequeueReusableCell(withIdentifier: "SecondTableViewCell") as! SecondTableViewCell 

     return cell.second_TableView.contentSize.height 
    } 

更新:

我已經調試的代碼,發現表2的電池的估計高特效表1的單元格的高度。即,如果表2的單元的估計高度是100並且這些單元是5個單元。然後這cell.second_TableView.contentSize.height給我500.哪個是錯誤的。因爲細胞有不同的高度10,20,30,40,10。

任何建議,將不勝感激。

謝謝!

回答

0

可能你正在因爲以下兩個原因

  1. 當你得到cell.second_TableView.contentSize.height那個時候你cell.second_TableView可能不會完全加載因此你得到錯誤高度的錯誤的結果。

  2. 您正在清除新的單元而不是現有的已加載單元。

請嘗試以下代碼:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
    { 

//Get existing cell rather deque new one 
     let cell = tableView_First.cellForRowAtIndexPath(indexPath) as! SecondTableViewCell 

//This will force table view to load completely 
    cell.second_TableView.layoutIfNeeded() 

     return cell.second_TableView.contentSize.height 
    } 

希望這將解決您的問題。

+0

感謝您的回答。但是這段代碼給了我「Bad _Access」。我檢查了錯誤https://stackoverflow.com/questions/35931478/why-tableview-cellforrowatindexpathindexpath-give-me-a-bad-access-error。你能建議現在做什麼? – Amanpreet

0

寫入這兩條線在viewDidLoad中,

tableView.estimatedRowHeight = 241

tableView.rowHeight = UITableViewAutomaticDimension

FUNC的tableView(_的tableView:UITableView的,heightForRowAt indexPath:IndexPath) - > CGFloat的{ return UITableViewAutomaticDimension }

相關問題