Swift 4 recipe: Self sizing table view

Dushyant Bansal
2 min readMar 2, 2018

UITableView requires auto layout to specify the height because there’s intrinsic content size doesn’t define the height.

We would like to modify this behaviour to be able to do something like this (Demo project on Github):

Once you have self sizing tableView, it’s very convenient to use them inside vertical stack views.

Self Sized Table View

Here TableView’s intrinsic content size adjusts the height to show all the rows. There’s one attribute named maxHeight to limit the height. Once maxHeight is achieved, adding more rows to the table view doesn’t result in height increase.

Here’s the swift recipe:

How to use it?

  1. After adding a table view in the interface builder:
  • Set the custom class to SelfSizedTableView
  • Don’t add any height constraint via auto layout for the table view

Your storyboard screen should look like this:

2. Define maxHeight for the tableView

override func viewDidLoad() {
super.viewDidLoad()
tableView.maxHeight = 372
}

Note: Another aspect to highlight is since our auto layout constraints don’t define the height of the table view, you might see missing constraintswarnings:

missing constraint

This warning is easy to fix. Go to the size inspector and set Intrinsic size -> Placeholder:

Auto layout is happy again

--

--