simplexity simplexity - 3 months ago 17
iOS Question

UITableViewCell sizing with optional image (Swift)

I am having a doozy of a time trying to figure this one out:

I have a

UITableViewCell
with a fixed sized
UIImage
(250 x 250) pinned to the top of the cell's
View
and a
UILabel
of variable text size underneath with its top pinned to the bottom of the
UIImage
and its bottom to the bottom of the cell's
View
.

I have a use case where an image is not always guaranteed and so the image view purposely collapses to
0
height so it does not break autolayout on the
UILabel
's top pinning.

I assumed that this would allow the
UITableViewCell
to shrink down to the size of the label but instead, it stays the default height and autolayout stretches the label's height (to maintain the pinning to the top and the bottom) with the text centered in the middle.

I used all the usual suspects,
UITAbleViewAutomaticDimension
and
estimatedRowHeight
blah blah (what you would probably suggest first!) and it was to no avail.

What am I doing wrong?

I did see something about changing the Priority for the constraints in IB to
250
instead of
1000
so they could break. And also some references to resizing the
UITableViewCell
manually (lame and nasty) by calling
requiredHeight()
on the
UILabel
which broke the layout, so what am I doing wrong here? Thanks!

Answer

I have a use case where an image is not always guaranteed

For this situation you can create 2 type of UITableViewCell: the first one with UIImageView and the second without it. Then, in cellForRowAtIndexPath init the cell you want.

Comments