[英]How to create dynamic tableview cell with dynamic tableview height in iOS
[英]TableView Cell Dynamic Height
我有一個UITableView(表1)。 在UITableView單元格內部,我還有另一個UITableView(表2)。
在Table 2
,行的高度為UITableViewAutomaticDimension
。
我的要求是-我希望Table 2
不能滾動,並根據Table 2
中行數獲取其完整高度。因此,根據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。
任何建議將不勝感激。
謝謝!
可能由於以下兩個原因導致錯誤的結果
當您獲取cell.second_TableView.contentSize.height
, cell.second_TableView
可能未完全加載,因此您得到了錯誤的高度。
您正在使新的單元出隊,而不是獲取現有的已加載單元。
請嘗試以下代碼:
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
}
希望這能解決您的問題。
在viewDidLoad中寫這兩行,
tableView.estimatedRowHeight = 241
tableView.rowHeight = UITableViewAutomaticDimension
func tableView(_ tableView:UITableView,heightForRowAt indexPath:IndexPath)-> CGFloat {return UITableViewAutomaticDimension}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.