简体   繁体   中英

How do I center 4 uibuttons with equal distance from each other?

I have 4 uibuttons. Each button MUST be 100x100. I want to center the 4 of them in the center of my screen (horizontally), but put them down vertically. I have no idea where to start, but i've heard stackviews might work? Not sure. I tried using basic constraints, but i was unable to get them to work.

here is what im trying to get: 在此处输入图片说明

Step 1 :- take 4 button in your Storyboard. Button1 , Button2 , Button 3 , Button4

Step 2 :- Give Fixed Height and width to All buttons .

在此处输入图片说明

Step 3 :- All 2 - 2 button's pair in 2 stackview.

在此处输入图片说明

Step 4 :- Set UIStackview Property for both .

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

在此处输入图片说明


在此处输入图片说明

Step 5 :- Add both Stackview in one Stackview

在此处输入图片说明

Step 6 :- Set Distribution = Fill equally Spacing =5 in main stackview (set According to your requirement)

在此处输入图片说明

Step 7 :- Now set Constrain to main stackview

      center Horizontally in container

      center vertically in container

        and select Update Frame.

在此处输入图片说明

Step 8 :- It's time for Output for All device .

在此处输入图片说明

I hope it will be helpful for you.

There are many ways, look one:

Idea:

  1. First put all buttons equals width and height constraint, and to one of the button add constraints to width and height 100.

  2. For each button center X/Y with respect to his parent. Constraint: Align Center X, Align Center Y

  3. Add offset to the constant (In interface builder):

    • Top Left button: Offset X of -60, Y of -60
    • Top Right button: Offset X of 60, Y of -60
    • Bottom Left Button: Offset X of -60, Y of 60
    • Bottom Right Button: Offset X of 60, Y of 60.

Quick Example (I did the constraint in IB): https://github.com/Abreu0101/ButtonLayout

========

Another option that you have is using transparent view's between the buttons, and center this view's (transparent), and add constraint to the buttons base on these views (Sometimes that's I tricky that I used, but all depends on what you need).

You can also try this without using UIStackView (if you need this to be work on < iOS 9) 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM