I have two labels in a horizontal stack view. The labels have numberOfLines
set to 0 so they will wrap infinitely, Vertical Content Compression Resistance set to 1000 so they will always be their full height, Horizontal Compression Resistance set to 250 because I want them to be able to be shrunk, and Content Hugging set to 1000 (both axes, because I always want the frame to hug the label). See:
Then that stack view is the only item in a self-sizing cell. It's constrained to the top, bottom, leading, and trailing margins. The stack view has the same compression resistance/content hugging as the labels.
At runtime, in my cellForRowAt indexPath function, I set the two labels to text of varying length. And since I've read elsewhere that layout can be a problem here, I also do:
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
However, when I run, I see some odd behavior initially. But when I scroll around, things start to look okay. It seems the problem has to do with cell reuse, but I can't figure out what's wrong.
On the left - the initial load. Note, the value label is being cut off entirely, and in the second cell, the proportional spacing doesn't seem to be working at all - the value label is very narrow when compared to the name label.
On the right - the table once I've scrolled to the bottom of the list and back to the top. This is exactly what I expect: labels are spaced proportionally based on their intrinsic content size. But how can I get this behavior without having to scroll around?
528 x 20.5
... if you restrict the width - either by setting constraints on the label or by embedding it in a stack view that has a width constraint, then it will wrap to multiple lines (if needed), and the intrinsic height will change... but if you have two labels, which one's intrinsic height do you want to get the priority? – DonMagcell.mainStackView.setNeedsLayout() cell.mainStackView.layoutIfNeeded()
(mainStackView is an outlet) instead ofcell.contentView.setNeedsLayout() cell.contentView.layoutIfNeeded()
. Does it change anything? – kamil3