UITableViewCell 内 UITableView 的动态行高 [英] Dynamic row heights of a UITableView inside a UITableViewCell

查看:33
本文介绍了UITableViewCell 内 UITableView 的动态行高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主"UITableView,我在其中使用了从 .xib 加载的不同单元格.其中一些单元格本身也有一个 UITableView.

I have a 'master' UITableView, in which I use different cells that are loaded from .xib's. Some of these cells themselves also have a UITableView.

现在我已将每个单元格的行高设置为原始 xib 大小.但是,我希望高度动态并对应于子"UITableView 中的行数.

For now I have set the row height of each cell to the original xib size. However, I would like to have the height dynamic and corresponding to the amount of rows in the 'child' UITableView.

我遇到了以下问题:

  • 在 ViewController 加载时,主 UITableView 需要为它拥有的每个单元格设置高度.
  • 到需要这个高度时,子 UITableView 还没有加载自己的单元格,因此还不是合适的大小.

我尝试了以下方法:

  • 首先,加载具有估计"高度的单元格
  • 单元格加载自己的 tableView 并调用刷新主 tableView

但是,在这种情况下,单元格将使用估计"高度来布置自己的行.因此它总是太大或太小.

However, in this case, the cell will use the 'estimated' height to lay out its own rows. Therefore it is always too big or too small.

我该如何解决这个问题?

How do I solve this problem?

推荐答案

第一种方法:

  1. 为子tableView 创建一个子类并覆盖intrinsicContentSize.

  1. Create a subclass for child tableView and override intrinsicContentSize.

     class MyOwnTableView: UITableView {
    override var intrinsicContentSize: CGSize {
        self.layoutIfNeeded()
        return self.contentSize
    }

    override var contentSize: CGSize {
        didSet{
            self.invalidateIntrinsicContentSize()
        }
    }

    override func reloadData() {
        super.reloadData()
        self.invalidateIntrinsicContentSize()
    }
}

  • 在界面生成器中,将子 tableView 的类更改为 MyOwnTableView(子类 UITableView).

  • In Interface builder change the class of your child tableView to MyOwnTableView (subclass UITableView).

    为父表和子表视图设置自动行高.

    Set automatic row height for both the parent and child table view.

        tableView.estimatedRowHeight = 60.0;
        tableView.rowHeight = UITableViewAutomaticDimension;
    

  • 第二种方法:1.为子tableView创建一个具有任意值的高度约束,并连接一个设置子tableView高度的IBOutlet.2. 将高度约束的常量设置为 tableView.contentSize.height

    Second Approach: 1. Create a height constraint with any value for child tableView and conect an IBOutlet that sets the child tableView height. 2. Set the height constraint's constant to tableView.contentSize.height

        self.tableViewHeight.constant = self.tableView.contentSize.height
    

    这篇关于UITableViewCell 内 UITableView 的动态行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆