【问题标题】:TableView Cell Dynamic HeightTableView 单元格动态高度
【发布时间】:2017-11-14 17:01:22
【问题描述】:

我有一个 UITableView(表 1)。在 UITableView 单元中,我有另一个 UITableView(表 2)。

Table 2 中,行的高度是UITableViewAutomaticDimension

我的要求是 - 我希望 Table 2 不应该滚动并根据其中的行数取其全高。所以,根据这个 Table 2 的高度,我需要设置 Table 1 的高度行高。

我正在使用 Table 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。

任何建议将不胜感激。

谢谢!

【问题讨论】:

    标签: ios uitableview swift3 row-height uitableviewautomaticdimension


    【解决方案1】:

    你得到错误的结果可能是因为以下两个原因

    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
        }
    

    希望这能解决您的问题。

    【讨论】:

    【解决方案2】:

    在 viewDidLoad 中写下这两行,

    tableView.estimatedRowHeight = 241

    tableView.rowHeight = UITableViewAutomaticDimension

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 返回 UITableViewAutomaticDimension }

    【讨论】:

      猜你喜欢
      • 2019-05-23
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 2017-04-18
      • 2016-10-19
      • 2021-11-25
      相关资源
      最近更新 更多