Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self sizing tableview

First of all this is not a question about how to automatically size the cells inside the tableview, moreover how to automatically resize the entire tableview.

So I have a scrollview which has a tableview and 2 other views as its subviews. The tableview's cells already automatically resize itself, again this question is not about the individual cells. However, the tableview does not resize at all.

What I have done: 1) Set up the tableview to have a top, bottom, leading and trailing constraint 2) Set the cells up to have auto layout enabled 3) * I do not know the cell size at build time 4) I have disabled scrolling mode on tableview

So long story short, how can I go along to get the tableview to resize itself?

Edit

The cells contain a label which can have various lines of text, so therefore the cells, which use auto layout, should then determine the height of the table view.

The following images show how the view is set up:

QuincholQuinchol 2

As you can see the tableview is only a small part of the view and since the scrollview from the tableview is deactivated there should, and aren't, any scrolling problems.

EDIT 2

This is actually how it should end however, i am calculating this on my own and everytime I want to make a small change to the cells the whole code, which calculates the height of the cell, needs to be rewritten and it is quite difficult for me to get the height just right.

Edit 3

Until now I had a height constraint on the tableview which I calculated manually, however removing this constraint and trying to let auto layout handle the tableview height size creates the following error:

Scroll View Need constraint for: Y position or height

I can conclude therefore that the tableview does not know how to automatically calculate the height based on its cells with autolayout.

like image 635
J.Paravicini Avatar asked Jun 04 '17 21:06

J.Paravicini


1 Answers

You don't need to create a height constraint or set frame whatsoever. Create a subclass of UITableView and recalculate its intrinsicContentSize every time its contentSize changes aka new data added or removed. Here is all you needed:

class SelfSizingTableView: UITableView {
    override var contentSize: CGSize {
        didSet {
            invalidateIntrinsicContentSize()
            setNeedsLayout()
        }
    }

    override var intrinsicContentSize: CGSize {
        let height = min(.infinity, contentSize.height)
        return CGSize(width: contentSize.width, height: height)
    }
}
like image 111
Linh Ta Avatar answered Sep 30 '22 21:09

Linh Ta