Episode #70

Autolayout with Cells

8 minutes
Published on June 6, 2013

This video is only available to subscribers. Get access to this video and 572 others.

Autolayout can be very powerful tool to provide layouts that are responsive to changes. In this episode we'll visit a case with UITableViewCells that makes using auto-layout somewhat frustrating, where constraints are applied to the cell itself instead of the cell's contentView.

Episode Links

The problem in this episode is that the auto layout constraints when added in the storyboard are applied to the UITableViewCell itself. When the cells go into editing mode, the cell's frame doesn't change, its contentView's frame does. In order to get our content to move out of the way for the delete icon to appear, we should be attaching constraints to the contentView instead of the cell's view.w

Moving constraints to the contentView

In the cell, override awakeFromNib:

- (void)awakeFromNib {
    [super awakeFromNib];

    for (NSLayoutConstraint *constraint in self.constraints) {
        [self removeConstraint:constraint];
        id firstItem = constraint.firstItem == self ? self.contentView : constraint.firstItem;
        id secondItem = constraint.secondItem == self ? self.contentView : constraint.secondItem;
        NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:firstItem
                                                                         attribute:constraint.firstAttribute
                                                                         relatedBy:constraint.relation
                                                                            toItem:secondItem
                                                                         attribute:constraint.secondAttribute
                                                                        multiplier:constraint.multiplier
                                                                          constant:constraint.constant];
        [self.contentView addConstraint:newConstraint];
    }
}

Now, going into editing model will move our views out of the way, to make room for the delete icon & button.