How can I center four buttons horizontally and vertically?


I would like to center four buttons horizontally and vertically.
Each of the buttons shall get a background image later, so I think it's important that the aspect ratio stays more or less the same, otherwise the pictures won't fit onto the button.

A screenshot of what it should look like: enter image description here

All buttons have the same size and should take up as much space as available (small margin, 10px or so, not more if possible). I don't know how to set the constraints that the application looks good on all devices (iPhone 5s and iPad 10.5").
The application must not necessarily run in all orientation modes.

How do I have to set the constraints?

Show source
| ios   | xcode   2017-11-29 19:11 2 Answers

Answers to How can I center four buttons horizontally and vertically? ( 2 )

  1. 2017-11-29 19:11

    This problem can easily be reduced to the problem of making a maximum square centered in its superview. You can do that easily with just four constraints:

    enter image description here

    The rest — the grid of buttons — just falls into your lap. For example, make my blue view a UIStackView containing a two UIStackViews, and there's your grid. Or you could do it with explicit constraints yourself.

    If this app can rotate, you might need two sets of constraints, one for when the width is less than the height, the other for when the height is less than the width. You would then have to swap them in code. But that's another issue, and is not difficult.

  2. 2017-11-29 19:11

    Add them to UIStackView, for placing them horisontally use horisontal value for axis property you can customize it with distribution, alignment and other properties of UIStackView. It's the easiest way

Leave a reply to - How can I center four buttons horizontally and vertically?

◀ Go back