ios 6:使用自动布局约束垂直居中UILabel

时间:2012-10-08 12:39:10

标签: iphone ios ios6 centering autolayout

我有UILabel我有时想在一个单元格中垂直居中。这必须以编程方式完成。我已经尝试添加以下约束来居中它(locName是UILabel):

[cell addConstraint:[NSLayoutConstraint constraintWithItem:cell
attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:cell.locName 
attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];

这是我得到的结果:

enter image description here

它看起来像是居中,但可能会改变UILabel的高度?

这是IB中的视图控制器:

enter image description here

如何以编程方式实现垂直居中?

3 个答案:

答案 0 :(得分:3)

这个怎么样: 除了居中约束之外,还要为cell.locName添加一个高度约束以使其更高。

[cell.contentView addConstraint:
    [NSLayoutConstraint constraintWithItem:cell.locName
                                 attribute:NSLayoutAttributeHeight
                                 relatedBy:NSLayoutRelationGreaterThanOrEqual
                                    toItem:nil
                                 attribute:NSLayoutAttributeNotAnAttribute
                                multiplier:1
                                  constant:20]];

答案 1 :(得分:2)

您可能正在点击单元格中已有的其他约束。添加约束不会消除其他约束 - 如果顶部和底部标签之间有间距,例如,为了满足此要求和新的居中约束,顶部标签的高度必须缩小。

您可能需要为这些其他约束设置出口并将其移除以实现居中设计。

答案 2 :(得分:0)

尝试在中心后达到UIlabel高度???

或者您可以以编程方式在自定义单元格中重新分配标签位置。

相关问题