Mobile App Development

UITableViewCell Editing with Autolayout

January 15, 2013

  • Felipe Laso Marsetti
  • 4

Hello and welcome to another Lextech iOS tutorial.

Today I want to share a tip on something I encountered while working on a personal project. This is related to table view cell prototypes inside a storyboard with Autolayout enabled.

Back in the non-Autolayout days you would create a custom cell and all subviews you put in it were added to the cell’s contentView property. When your table view went into editing mode, things would work as expected because the cell’s content view would be properly resized to fit the editing accessories. With Autolayout this is not the case, and so I did a little digging in StackOverflow to find a simple solution to this problem without having to use NIBs or disable Autolayout.

I’ve created an iOS project based on the Master-Detail Application template and added a custom cell to the storyboard as shown below:

Custom Table View Cell

I gave my cell an identifier and also modified my table view data source methods accordingly so we should the row number and the current date.

Take a look at what happens with custom cells when in editing mode:

Cell Editing Overlap Problem

Notice how the delete accessory overlaps with the number label setup in the custom cell. After doing some research it seems that the problem with custom cells is that constraints are being added between the labels (or any other cell subviews) to the cell’s view and not the cell’s content view. The solution to the problem is to override awakeFromNib in your cell’s custom subclass, loop through each of the constraints and set them between the cell’s content view and the subview element.

This is the code you can use to achieve the desired result:

- (void)awakeFromNib
[super awakeFromNib];

for (NSLayoutConstraint *cellConstraint in self.constraints)
[self removeConstraint:cellConstraint];

id firstItem = cellConstraint.firstItem == self ? self.contentView : cellConstraint.firstItem;
id seccondItem = cellConstraint.secondItem == self ? self.contentView : cellConstraint.secondItem;

NSLayoutConstraint* contentViewConstraint = [NSLayoutConstraint constraintWithItem:firstItem

[self.contentView addConstraint:contentViewConstraint];

With the method in place what you get is the result you expected, as seen in the screenshot below:

Cell Editing Fixed

Hopefully you can find this code snippet useful in future projects that use custom cells, storyboards and Autolayout.

Thank you for reading and feel free to download the Xcode project for reference.

Until next time,
Feli 🙂