Question

I’m pawing my way through AutoLayout for the first time (and not using IB/storyboards to do so), and I’m trying to do some simple vertical alignment in a UITableViewCell, of a title label and a detail label, laid out like this:

—————— 
Padding
Title Label
Spacing (3px)
Detail Label
Padding
——————

The part I’m strugging with is getting the two “Padding” constraints there to be kept equal at all times. Everything else works, but the labels are either at the very top or very bottom of the cell.

I’m actually using Masonry to implement this, and it looks like this:

// Constrain the title label at the top of the label container.
[title makeConstraints:^(MASConstraintMaker *make) {
    make.top.greaterThanOrEqualTo(self.contentView.top).with.priorityLow();
}];

// Constrain the detail label to the bottom of the label container.
[detail makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.titleLabel.bottom).with.offset(3).with.priorityHigh();
    make.bottom.lessThanOrEqualTo(self.contentView.bottom).with.priorityLow();
}];

I need the make.top line from the title constraint and the make.bottom line from the detail constraint to always maintain the same value, so that the title/spacing/detail sits in the middle.

What am I missing here?

Was it helpful?

Solution

This is something you can't do just through normal constraints.

You can't make spaces equal to each other.

What you need to do is use invisible "spacer" views and make their heights equal.

So you would have something like...

// in pseudo VFL
V:|[topSpacer][titleLabel]-[subTitleLabel][bottomSpacer(==topSpacer)]|

Make the topSpacer and bottomSpacer alpha = 0 or hidden = YES and it will hide them but they will act as layout scaffolding.

By doing this the gap above the titleLabel will be the same as the gap below the subTitleLabel.

OTHER TIPS

Put your Title and Detail Labels into a subview. Then create constraints for that subview with respect to the enclosing cell. Since you want the top and bottom padding to be equal, you can simply choose Vertical centering as the constraint.

Also, assuming iOS 8, I believe you can allow the table cell itself to resize itself to accommodate the subview.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top