使用自动布局和约束设置按钮

时间:2016-04-19 09:33:41

标签: ios constraints ios-autolayout

屏幕上有4个按钮。 我想将所有4个按钮放在屏幕上的距离与所有屏幕中的图像相同,即4s,5s,6和6plus。

我添加的约束

Button 1 : 
Top , leading and trailing

Button 4: 
Bottom , leading and trailing

Button 2 : 
Leading
trailing
top to button 1

Button 3: 
    Leading
    trailing
    top to button 2
    bottom to button 4

但是我无法以相同的距离实现按钮2和按钮3。 我想通过使用autolayout和约束来实现这一点。

请建议。

enter image description here

3 个答案:

答案 0 :(得分:2)

使用Autolayout完成解决方案。

因为,您在视图中使用偶数个按钮,因此您需要在视图的中心(X和Y)位置添加高度为2的UILabel。 以下限制将适用于所有屏幕,即4s,5s,6和6plus。

[注意:如果是奇数按钮,将使用中心按钮代替标签]

<强>约束:

标签: 1.中心-X 2.中心-Y 3.修复高度和宽度(高度= 2,宽度=无限制)

按钮1:

  1. 从底部到BUTTON 2(例如70)

  2. 中心-X

  3. 修复高度宽度

  4. 按钮2:

    1. 返回BUTTON 3(例如70)

    2. 底部到LABEL(例如34)

    3. 中心-X

    4. 修复高度宽度

    5. 按钮3:

      1. 返回LABEL(例如34)

      2. 从底部到BUTTON 4(例如70)

      3. 中心X

      4. 修复高度宽度

      5. 按钮4:

        1. 排在BUTTON-3之前(例如70)

        2. 中心-X

        3. 修复高度宽度

答案 1 :(得分:1)

这可以通过Interface Builder实现:

如果您想在iOS9之前支持iOS版

  1. 您需要使用隐藏的间隔UIViews(下图中的橙色)
  2. 他们的身高应该相等
  3. 按钮及其相邻间隔视图之间的距离应设置为0
  4. enter image description here

    这使您能够为每种设备类型创建自适应布局(如果您将间隔器的视图高度设置为与超视图的高度成比例):

    enter image description here

    对于 iOS9 + ,只需使用带有垂直轴和所需分配空间的UIStackView

    enter image description here

答案 2 :(得分:0)

试试这个,

你的约束应该是,

按钮1 - 顶部,领先&amp;容器中的尾随或水平中心。

按钮2 - 顶部,领先&amp;容器中的尾随或水平中心。

按钮4 - 底部,前导&amp;容器中的尾随或水平中心。

按钮3 - 底部,领先&amp;容器中的尾随或水平中心。

现在对于按钮2采取,顶部约束的出口(按住ctrl +从约束拖动到类)和从按钮3采取底部约束的出口。

例如你的插座是button2Outlet&amp; button3Outlet分别。

所以,来自viewdidload,

CGFloat constantVslue = self.view.frame.size.height - (4 * buttonHeight) - 40 (top distance of button 1 + bottom distance of button 4); 

//40 is distance from top and bottom of 1st and 4th button respactively in my case (20+20) and in my case my button height is 30 so total 120.

CGFloat distance = constantVslue/3;

self.button2Outlet.constant = distance;
self.button3Outlet.constant = distance;

希望这会有所帮助:)