Just getting my feet wet with iOS development, so I hope I’m getting the right level of detail here…
I have a UILabel, loaded in a Table cell created via a .xib. Actually several labels, one of which is of varying length (and therefore varying wrapped height). heightForRowAtIndexPath, etc. are properly overridden, and the required height for both labels is being calculated correctly and assigned to each’s .frame
Once both sizes have been set, I set the frame.origin.y of the smaller (fixed length, always one row high) label to match that of the larger label. This works as far as can be seen stepping through cellForRowAtIndexPath but on initial display of the newly-created cell, the origin seems to be not-quite-vertically-centered in the container, as opposed to stuck up top.
After clicking “through” the cell to a different view, and returning to the (now-reused, and presumably already properly-sized container), the position is set as before, and it appears where I expected it to.
It seems like the container is being resized after cellForRowAtIndexPath returns, and that somewhere in there a new position is found for our label; this would explain why reusing the cell later fixes the problem.
I’ve tried every apparently-sane combination of inner and outer Mode and Baseline settings, stretch settings, etc. At a loss for explanations and/or workarounds.
Update:
A suggestion on the Changing the position of custom UIButton in custom UITableViewCell question solved the problem. The solution was to subclass UITableViewCell and override layoutSubviews, thereby getting a chance to re-position the sub-elements after the TableView had done its normal positioning. Will close this once either that person responds here, or the bounty expires and I’ll answer myself, with code.
If I do any complex layout in a UITableViewCell I try to keep it out of cellForRowAtIndexPath. One option is to do layout in
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPathbut I prefer to encapsulate layout in a custom UITableViewCell class.Make your own UITableViewCell subclass. Create and add the custom button / label / view to the cell’s contentView in your init method, or create and add it lazily via an accessor property. Override layoutSubviews and postion the button as desired.
Something like this: