簡體   English   中英

TableView單元格動態高度

[英]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。

任何建議將不勝感激。

謝謝!

可能由於以下兩個原因導致錯誤的結果

  1. 當您獲取cell.second_TableView.contentSize.heightcell.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
    }

希望這能解決您的問題。

在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM