Auto layout with custom UITableViewCell

2019-03-15 14:15发布

问题:

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.

回答1:

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.

  1. Open your story board and select the PlayerCell and expand its constraints.
  2. Select the constraint " Horizontal Space (20) " and in the Attributes inspector set its priority to any lower value.
  3. 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]];



回答2:

In my case I have removed right constraint and then I have added it again but this time with "constraint to margin" checkbox unchecked. This checkbox is checked as default.