在代码中使两个AutoLayout约束相等?

时间:2014-01-16 10:00:21

标签: ios objective-c uitableview autolayout nslayoutconstraint

我第一次穿过AutoLayout(并没有使用IB /故事板这样做),我正试图在标题标签的UITableViewCell中做一些简单的垂直对齐还有一个细节标签,如下所示:

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

我正在考虑的部分是让两个“填充”约束始终保持相同。其他一切都有效,但标签位于单元格的顶部或底部。

我实际上是使用Masonry来实现它,它看起来像这样:

// 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();
}];

我需要make.top约束中的title行和make.bottom约束中的detail行始终保持相同的值,以便标题/间距/细节位于中间。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:6)

这是你不能通过正常约束做的事情。

你不能让空格彼此相等。

你需要做的是使用不可见的“间隔”视图,使它们的高度相等。

所以你会有类似......

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

创建topSpacer和bottomSpacer alpha = 0hidden = YES,它会隐藏它们,但它们将充当布局脚手架。

通过这样做,titleLabel上方的间隙将与subTitleLabel下方的间隙相同。

答案 1 :(得分:0)

将标题和详细信息标签放入子视图中。然后针对封闭单元格创建该子视图的约束。由于您希望顶部和底部填充相等,因此您只需选择“垂直居中”作为约束。

另外,假设iOS 8,我相信您可以允许表格单元格自身调整大小以适应子视图。