0

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

在行的Table 2高度是。UITableViewAutomaticDimension

我的要求是 - 我希望它Table 2不应该滚动并根据其中的行数取其全高。所以,根据 thisTable 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。

任何建议将不胜感激。

谢谢!

4

2 回答 2

0

在 viewDidLoad 中写下这两行,

tableView.estimatedRowHeight = 241

tableView.rowHeight = UITableViewAutomaticDimension

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

于 2017-06-14T06:55:54.570 回答
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
    }

希望这能解决您的问题。

于 2017-06-13T05:04:58.013 回答