UITableView within a UITableViewCell with dynamic height

前端 未结 3 1978
执笔经年
执笔经年 2021-01-27 07:50

So I\'m trying to build something rather intricate - potentially more than what the picture below shows. Anyway..

I\'m trying to have a UITableView inside o

3条回答
  •  春和景丽
    2021-01-27 08:41

    You can subclass UITableView and turn it into an "auto-sizing" table view, based on its contents:

    final class ContentSizedTableView: UITableView {
        override var contentSize:CGSize {
            didSet {
                invalidateIntrinsicContentSize()
            }
        }
        override var intrinsicContentSize: CGSize {
            layoutIfNeeded()
            return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
        }
    }
    

    Now, the table view will behave very similar to a multi-line UILabel --- just set up your constraints in the same way.

    Two notes:

    1) Disable scrolling on the ContentSizedTableView - not necessary but will probably be a better UX for your case.

    2) When you lay this out in your prototype cell, it will need a Height constraint to satisfy IB / Storyboard. So, add either

    • a >= height constraint (so you have a minimum height even if you have no rows), or
    • give it a "Placeholder" height constraint, or
    • give the height constraint a low priority

    Here is an example using a ContentSizedTableView in a scroll view. Same idea, and should make it clear how to use it:

    https://stackoverflow.com/a/56840758/6257435

提交回复
热议问题