bigpotato
bigpotato

Reputation: 27497

Xcode: How to make a grid of 3x3 images take up 1/3 of the width and height?

I am trying to make a view with 9 buttons, all that have 1/3 of the screen height and 1/3 of the screen width. I'm using storyboards. This is what I have now:

enter image description here

As you can see, they aren't in the right positions. Is there an easy way to get all the buttons to have the proper dimensions?

Upvotes: 0

Views: 371

Answers (2)

rickster
rickster

Reputation: 126107

@medvedNick has the right idea, but if you're targeting iOS 9 or later, you can save yourself from managing quite so many Auto Layout constraints by using UIStackView.

Just make one vertical stack view containing three horizontal stack views (or vice versa), each of which has three buttons, and set all the stack view's distribution to Fill Equally. You'll still need a couple sets of constraints — one to make the outer stack view fill the screen, and one to make the inner horizontal stack views fill the width of the outer vertical stack view.

At run time, this gets you roughly the same effect as setting your own layout constraints (because UIStackView creates constraints to manage its subviews)... but it makes the constraint setup simpler for you at design time. For example, if you want this whole grid of buttons to fill only half the screen, you can just change the constraint that sets the width (or height) of the outer stack view.

(This example doesn't leverage all that UIStackView can do, by the way. If your views aren't all supposed to be lined up in a grid, if they change size, or if you add/remove views at runtime, UIStackView can be even more help.)

Upvotes: 1

medvedNick
medvedNick

Reputation: 4510

The only thing you need is to set correct constraints for all buttons.

These are:

  1. Leading constrains with constant 0 for all buttons
  2. Top constraints with constant 0 for all buttons
  3. Trailing constrains with constant 0 for all buttons
  4. Bottom constraints with constant 0 for all buttons
  5. Equal width constraints for all buttons
  6. Equal height constraints for all buttons

How to:

  1. Select all buttons
  2. Add leading, top, width and height constraints

like this

  1. Select left-row and bottom buttons
  2. Add right and bottom constraints as in step 2

Make sure you turn off Constrain to margins when adding constraints of 1-4

Upvotes: 1

Related Questions