When I want to have a custom cell, I generally add a UIView
subclass to the cell's content view. For the layout of my subviews I use a nib. Then I wire up the nib to my UIView
subclass. My issue is how to dynamically size content. Say my view has a lot UILabels
inside it. I use layoutSubviews
to position all the subviews - but it is only until that is done that I truly know the height of my cell. So currently in tableView:heightForRowAtIndexPath
I setup my subview and call layoutIfNeeded
so everything is positioned properly. Now I know the height of my cell and return it in the tableView:heightForRowAtIndexPath
method. But now when tableView:cellForRowAtIndexPath
is called the cell that I am given has a height of 44.0
. When I added my subview to it - my subview is outside of its parent's bounds. Then when the cell is later resized in iOS to the height that I said I needed, my content is thrown off because of my autoresizingMask
. Just trying to figure out if this is an issue others deal with or if I'm approaching it completely wrong. It just seems backwards that we ask for the height, then create a cell that is not that height.
Asked
Active
Viewed 1,073 times
1

Brian
- 3,571
- 7
- 44
- 70
1 Answers
2
Unfortunately, this is how UITableViews work: You need to provide the heights before the UITableViewCells are actually rendered. And yes, everyone has to deal with it. :)
You could create an NSArray, add all your custom contentViews, set their frame
according to the expected contentView bounds and then use this array as data source in tableView:heightForRowAtIndexPath:
and tableView:cellForRowAtIndexPath:
. While this isn't exactly efficient, it works fine for small data sets.
Also, here's a nice tutorial with this topic: UITableViewCell Dynamic Height (by Matt Long)
A similar question on SO: How can I do variable height table cells on the iPhone properly?

Community
- 1
- 1

Andreas Ley
- 9,109
- 1
- 47
- 57