I can't achieve a self sizing UITableViewCell
with a UIStackView
inside it.
For the UITableViewCell
I'm doing something like this:
On code I'm doing this:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 80
}
But when I run the app, the UITableViewCell
s doesn't resizes:
What do I miss to make the UITableViewCell
self sizing with a UIStackView
inside it?
A streamlined interface for laying out a collection of views in either a column or a row.
A view that presents data using rows in a single column.
If you specify UITableView.automaticDimension from tableView (_:heightForRowAt:), UITableView will calculate the cell's height based on its autolayout constraints, so you don't have to define the height yourself.
The proper way to set the UIScrollView including UIStackView is to use option #1. Set the width of the UIStackView equal to the UIViewController view. Also add the height constraint to UIStackView marked as removed at build time.
If horizontal, you have to update the leading, and trailing constraints priority of your arranged subviews. If vertical, you have to update the top and bottom constraints priority of your arranged subviews. 999 is enough and will let the UIStackView work smoothly.
Let’s create our View Controller. Right-click the View Controllers group, select New File and choose Cocoa Touch Class in the panel that appears. Then create a sub-class of UITableViewController.
The cell resizing is working fine. Your problem is that you set a fixed height for the Stack View.
The View in the horizontal Stack View has its height
set to 64
, most likely with its standard priority set to 1000
. This Stack View most likely has its distribution set to Fill
. You basically told the Stack View that the containing image has to exactly fill the Stack View with a height of 64
. This is also limiting the Stack View to 64
and with it the vertical Stack View besides the View. Change the distribution of the horizontal Stack View that contains the View to Center
if you want the vertical Stack View next to the View to get bigger than 64
.
The trick to getting Auto Layout for self sizing cells to work on a UITableViewCell is to ensure you have constraints to pin each subview on all sides — that is, each subview should have leading, top, trailing and bottom constraints. Then, the intrinsic height of the subviews will be used to dictate the height of each cell.
Here is a nice tutorial that will get you through it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With