I am configuring a custom UITableViewCell using a prototype cell in a Storyboard. However, all the UILabels (and other UI elements) do not seem to be added to the cell’s contentView, instead being added to the UITableViewCell view directly. This creates issues when the cell is put into editing mode, as the content is not automatically shifted/indented (which it would do, if they were inside the contentView).
Is there any way to add the UI elements to the contentView when laying out the cell using Interface Builder/Storyboard/prototype cells? The only way I have found is to create everything in code and use [cell.contentView addSubView:labelOne] which wouldn’t be great, as it is much easier to layout the cell graphically.
On further investigation (viewing the subview hierarchy of the cell) Interface Builder does place subviews within the cell’s
contentView, it just doesn’t look like it.The root cause of the issue was iOS 6 autolayout. When the cell is placed into editing mode (and indented) the
contentViewis also indented, so it stands to reason that all subviews within thecontentViewwill move (indent) by virtue of being within thecontentView. However, all the autolayout constraints applied by Interface Builder seem to be relative to theUITableViewCellitself, rather than thecontentView. This means that even though thecontentViewindents, the subviews contained within do not – the constraints take charge.For example, when I placed a
UILabelinto the cell (and positioned it 10 points from the left-hand side of the cell) IB automatically applied a constraint “Horizontal Space (10)”. However, this constraint is relative to theUITableViewCellNOT thecontentView. This means that when the cell is indented, and thecontentViewmoves, the label stays put as it is complying with the constraint to remain 10 points from the left-hand side of theUITableViewCell.Unfortunately (as far as I am aware) there is no way to remove these IB created constraints from within IB itself, so here is how I solved the problem.
Within the
UITableViewCellsubclass for the cell, I created anIBOutletfor that constraint calledcellLabelHSpaceConstraint. You also need anIBOutletfor the label itself, which I calledcellLabel. I then implemented the-awakeFromNibmethod as per below:In summary, the above will remove the horizontal spacing constraint which IB automatically added (as is effective against the
UITableViewCellrather than thecontentView) and we then define and add our own constraint to thecontentView.In my case, all the other
UILabelsin the cell were positioned based upon the position of thecellLabelso when I fixed up the constraint/positioning of this element all the others followed suit and positioned correctly. However, if you have a more complex layout then you may need to do this for other subviews as well.