Centering two buttons with Cocoa Auto Layout

后端 未结 7 1917
抹茶落季
抹茶落季 2021-02-03 22:13

I have a problem with Cocoa Auto Layout and can\'t get my head around this problem. All I\'d like to achieve is to have two buttons always centered in a view as depicted below.<

7条回答
  •  青春惊慌失措
    2021-02-03 23:10

    If you have fixed width buttons and you want fixed distance between two then following steps can do the work :

    1. add Width and Height constraint to button1 Example value: 100 height and 100 width.
    2. select both buttons and add constraint Equal Widths and Equal Heights.
    3. add Horizontal Spacing between button1 and button2. or we can say add Leading Space to button2 from button1. Example value : 150
    4. select button1 and add constraint Horizontally in Container with -125 value.
    5. add other constrains like Vertical Spacing to Container etc as per needed.

    Example value 125 is equals to (button1 width / 2) + (Horizontal Spacing/2) which is 100/2 + 150/2 = 125.

    So adding Horizontal in Container to -125 will move the buttons to left and that will make this layout center in screen.

    Example layout and Constraints images attached below :

提交回复
热议问题