Custom UITableViewCell Delete Woes

I’ve just spent some time solving an issue in my iOS app. I have a custom UITableViewCell with some UILabels. When I delete a row on the UITable, the standard confirm delete animation happens. With the standard UITableViewCells, this triggers an animation where the cell labels move to the right, to make room for the delete icon on the left. With my custom UITableView, the UILabels weren’t moving to the right and were being squashed by the delete control.

It turns out that this problem is caused by the NSLayoutConstraint constructed in the storyboard. XCode creates a constraint bound to the cell itself, rather than the contentView. This was solved thanks to this StackOverflow post, that details the solution.

You need to create an outlet for the NSLayoutConstraints you want to delete and bind them in the storyboard. Then in awakeFromNib, you delete those constraints and add new ones. I’ve added my code for doing it with 2 UILabels below.

- (void)awakeFromNib {

    // Remove the IB added horizontal constraint, as that's effective
    // against the cell not the contentView
    [self removeConstraint:self.cellLabelHSpaceConstraint1];
    [self removeConstraint:self.cellLabelHSpaceConstraint2];
    self.cellLabelHSpaceConstraint1 = nil;
    self.cellLabelHSpaceConstraint2 = nil;

    // Create a dictionary to represent the view being positioned
    NSDictionary *labelViewDictionary1 = @{ @"_lblName" : self.lblName     };
    // Create the new constraint

    NSArray *constraints1 =     [NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[_lblName]"     options:0 metrics:nil views:labelViewDictionary1];
        // Add the constraint against the contentView
    [self.contentView addConstraints:constraints1];

    // Create a dictionary to represent the view being positioned
    NSDictionary *labelViewDictionary2 = @{ @"_lblDesc" : self.lblDesc     };
    // Create the new constraint
    NSArray *constraints2 =     [NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[_lblDesc]"     options:0 metrics:nil views:labelViewDictionary2];
    // Add the constraint against the contentView
    [self.contentView addConstraints:constraints2];
}