Search code examples
iosswiftuitableviewautolayout

TableView resizing parent view iOS


This is a problem that has been bugging me for quite some time.

Assume a view that holds a tableView with X items. The goal is to make that view resize so that it is as high as the contents of the tableView.

An approach

Calculate the contents of the tableView in total ( e.g if there are 5 rows and each is 50 units high, its just a multiplication matter ). Then set the tableView constrained at a 0 0 0 0 into the view and set the view height to 250.

This works well for fixed height cell sizes. However!

a) How would the problem be approached for dynamic height cells though with complex constraints in a scenario where resizing happens automatically and the tableHeightForRow is set to UITableViewAutomaticDimension?

b) An idea could be using tableView.contentSize. However when would we retrieve that value safely in order to set the parent view frame accordingly? Is that even possible?

Thanks everyone


Solution

  • If you have a UITableView subclass, you can set up a property observer on the contentSize like this:

    override var contentSize: CGSize {
            didSet {
                // make delegate call or use some other mechanism to communicate size change to parent
            }
        }
    

    The most straightforward approach to this in my opinion is to use Autolayout. If you take this approach, you can use the contentSize to automatically invalidate the intrinsicContentSize which is what autolayout uses to dynamically size elements (as long as they don't have higher priority placement constraints restricting or explicitly setting their size).

    Something like this:

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

    Then, just add your table view to your parent view hierarchy with valid placement constraints and a content hugging/compression resistance of required.