pableiros
pableiros

Reputation: 16022

How can I make self sizing UITableViewCell with a UIStackView inside it

I can't achieve a self sizing UITableViewCell with a UIStackView inside it.

For the UITableViewCell I'm doing something like this:

ui

On code I'm doing this:

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.estimatedRowHeight = 80
}

But when I run the app, the UITableViewCells doesn't resizes:

result

What do I miss to make the UITableViewCell self sizing with a UIStackView inside it?

Upvotes: 11

Views: 8102

Answers (5)

amirkrd
amirkrd

Reputation: 203

open class IntrinsicHeightTableView: UITableView {

open override var contentSize: CGSize {
    didSet { invalidateIntrinsicContentSize() }
}

open override var intrinsicContentSize: CGSize {
    layoutIfNeeded()
    return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
} }

Upvotes: 0

RyuX51
RyuX51

Reputation: 2877

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.

Upvotes: 4

wm_j_ray
wm_j_ray

Reputation: 144

Do you have multi line labels? If so make sure you have the lines property in IB set to 0 not 1.

Pin top and bottoms of stackView.

If that doesn't do it, check these:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Upvotes: 2

wm_j_ray
wm_j_ray

Reputation: 144

Try pinning the stack view itself. Remember the stackView has the responsibility to equally space, evenly distribute, etc., so it needs to use constraints between itself and its superView to figure all that out.

Here's an apple explanation.

HTH

Upvotes: 0

wm_j_ray
wm_j_ray

Reputation: 144

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.

Upvotes: 1

Related Questions