如何布局UILabel和UIButton并使它们居中?

时间:2016-10-22 19:05:56

标签: ios autolayout uistackview

我想在按钮旁边布置标签,如下所示:

[--[UILabel]-[UIButton]--]

我希望它们在superview中居中,考虑到UILabel和UIButton具有动态文本长度。

如何使用AutoLayout或UIStackViews?

谢谢,

4 个答案:

答案 0 :(得分:2)

如何将视图封装在视图中并将该视图居中于superview? 类似的东西:

主视图[集中视图[标签 - 按钮]]

Centralize the wrapper view to center of superview. Don't give fix width of button or label, just stick them horizontally

答案 1 :(得分:1)

将标签和按钮对齐到superview。如果您正在使用故事板或XIB文件,请选择标签Horizontally Centered Constraint,然后在尺寸检查器中(在Xcode的右栏,第5项)选择Label.Trailing而不是{{1 }}。并给它一个值(或零,无论你想要什么。这将是标签和视图中心之间的常量)。

设置后,Label.X中标签的Center X Alignment Constraint应如下所示:

UILabel's Center X Alignment Constraint in Size Inspector

对按钮执行相同操作。但是这一次,选择Size Inspector而不是Button.Leading并给它一个常量。 设置后,Button.X中按钮的Leading Alignment Constraint应如下所示: UIButton's Leading Alignment Constraint in Size Inspector

通过此解决方案,Label和Button将彼此独立。您可以单独决定其他属性。

您的结果应如下所示: Autolayout UILabel and UIButton

答案 2 :(得分:0)

在StackView中放置标签和按钮,并为StackView提供约束(中心水平,中心垂直)到superview

答案 3 :(得分:-1)

使用AutoLayout。根据您的确切情况调整:

  1. 将标签和按钮放置在视图中心,如图所示
  2. 锁定前导,尾随和顶部约束。 (不要限制底部或高度)
  3. 将标签和按钮限制为相等的宽度。
  4. 将标签设置为0行。
  5. 将按钮设置为自动换行。
  6. 享受。
  7. enter image description here