Swift 4 recipe: Self sizing table view
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?
- 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 constraints
warnings:
This warning is easy to fix. Go to the size inspector and set Intrinsic size -> Placeholder: