如何将4个uibutton相互间隔相等的中心?

时间:2016-05-19 18:44:12

标签: ios swift uibutton autolayout constraints

我有4个uibuttons。每个按钮必须是100x100。我想将它们中的4个放在我的屏幕中央(水平),但是将它们垂直放下。我不知道从哪里开始,但我听说堆栈视图可能有用吗?不确定。我尝试使用基本约束,但我无法让它们工作。

这是我想要得到的: enter image description here

3 个答案:

答案 0 :(得分:3)

第1步:在故事板中按4按钮。 Button1,Button2,Button 3,Button4

第2步: - 为所有按钮指定固定高度和宽度。

enter image description here

第3步: - 2个stackview中的所有2 - 2按钮对。

enter image description here

第4步: - 为两者设置UIStackview属性。

      Distribution -> Fill Equally
           Spacing -> 5 (as per your requirement)

enter image description here

enter image description here

步骤5: - 在一个Stackview中添加两个Stackview

enter image description here

第6步: - 在主堆栈视图中设置Distribution = Fill equally Spacing =5(根据您的要求设置)

enter image description here

第7步: - 现在将Constrain设置为主stackview

      center Horizontally in container

      center vertically in container

        and select Update Frame.

enter image description here

步骤8: - 现在是输出所有设备的时间。

enter image description here

我希望它会对你有所帮助。

答案 1 :(得分:0)

有很多方法,看一下:

点子:

  1. 首先将所有按钮等于宽度和高度约束,然后将一个按钮添加约束宽度和高度100。

  2. 对于每个按钮中心X / Y相对于其父母。 约束:对齐中心X,对齐中心Y

  3. 向常量添加偏移量(在界面构建器中):

    • 左上按钮:偏移X为-60,Y为-60
    • 右上方按钮:偏移X为60,Y为-60
    • 左下方按钮:偏移X为-60,Y为60
    • 右下方按钮:偏移X为60,Y为60。
  4. 快速示例(我在IB中做了约束): https://github.com/Abreu0101/ButtonLayout

    ======

    你有另一个选择是在按钮之间使用透明视图,并将这个视图放在中心(透明),并根据这些视图添加对按钮的约束(有时候我使用的很棘手,但都取决于你需要什么)。

答案 2 :(得分:0)

您也可以在不使用UIStackView的情况下尝试此操作(如果您需要将其用于< iOS 9)enter image description here