如何将两个并排的UILabels水平居中?

时间:2015-02-01 11:39:13

标签: ios objective-c xcode autolayout

我有一系列我希望水平居中的标签(即沿X轴),如下所示:

thing1: value1
thing2: value2
etc.

Autolayout似乎不允许这样做。即使我将两者结合在一起并使用指南将对中心对中,但中心约束仅适用于对中的第一个标签。

各种"事物"将有不同的长度,我想冒号排队(右对齐)和左边的值排队(左对齐)。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

This is easy to do in code. The x-offset of the first label should be half the difference between the width of the parent view and the sum of the widths of the two labels. For example:

CGFloat xOffset = ((parentView.frame.size.width - 
                   (view1.frame.size.width + view2.frame.size.width)) / 2);

// now position the first label using this offset
view1.frame = CGRectMake(xOffset, 
                         view1.frame.origin.y, 
                         view1.frame.size.width,
                         view1.frame.size.height);

// and position the second view relative to the first
view2.frame = CGRectMake(CGRectGetMaxX(view1.frame),
                         view2.frame.origin.y,
                         view2.frame.size.width,
                         view2.frame.size.height);
相关问题