How do I get the contents of a custom UITableViewCell to shift and resize using Auto Layout?
To make the issue more clear, I've assigned the contentView
of my custom cell to have a light gray background color. To reduce this to the smallest problem possible, my custom cell has only one UIImageView
named ratingImageView
that shows some number of yellow stars; three such cells can be seen in the image below.
My ratingImageView
has only 4 constraints; (1) width =81, (2) height =40, (3) align center Y to superview, and (4) trailing space to superview =20. I would have expected the trailing space to superview constraint to force the image view to the left when the standard delete button appears on swipe to delete. It does not, however, as can be seen in the image below.
I've tried many different combinations of constraints and cannot make the ratingImageView
shift as I would expect.
I encountered this problem by working through a good introductory Storyboard tutorial. I had no problem making this work using good old struts and springs, but I decided to try it with Auto Layout and have had no luck.
Image view without an image selected has no intrinsic content size, hence we need to set an explicit height constraint for it. The key to achieve dynamic height table view cell is to let Auto Layout know how to calculate the height of the cell.
Auto layout is a property you can add to frames and components. It lets you create designs that grow to fill or shrink to fit, and reflow as their contents change. This is great when you need to add new layers, accommodate longer text strings, or maintain alignment as your designs evolve.
A view that presents data using rows in a single column.
I had the same issue when I turned Autolayout ON
for the tutorial.
The issue is because of constraint Horizontal Space (20)
. The priority of this constraint is set to 1000
by default which mean high priority. So the imageView is obeying the constraint and making itself stay in its position without relocating corresponding to UITableViewCell's (PlayerCell in this case) content view when delete
button is displayed.
In Collaboration with my colleague we found the solution for this problem. Adding the constraints to the ratingImageView programmatically solved this issue.If anyone has a better solution than this please post here.
Horizontal Space (20)
" and in the Attributes inspector set its priority to any lower value.In PlayersViewController.m file add the following code in cellForRowAtIndexPath
tableView's delegate method:
UIImageView *ratingImageView = cell.ratingImageView;
NSDictionary *dict = NSDictionaryOfVariableBindings(ratingImageView);
[cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[ratingImageView]|" options:0 metrics:nil views:dict]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With