TOPCOD3R
TOPCOD3R

Reputation: 154

How to center multiple buttons in a ViewController?

I have 3 buttons which I would like to center at the top of my ViewController, so that they remain centered regardless of the screen size of the iPhone or iPad. I have tried to:

None of these methods seem to work for me and I cannot figure out how to solve this. I have looked around for solutions but I cannot find anything that allows me to do this.

enter image description here

Upvotes: 0

Views: 302

Answers (1)

Caleb
Caleb

Reputation: 125037

None of these methods seem to work for me and I cannot figure out how to solve this. I have looked around for solutions but I cannot find anything that allows me to do this.

It's easy to "center" the group of buttons using nothing but constraints. Here's an example:

contstraints on 3 buttons

To achieve this, I first constrained Button 2 to the horizontal center of the safe area, and I constrained it's top to the safe area's top plus 128px. Then I constrained the top of Button 1 and Button 3 to be equal to the top of Button 2. Finally, I constrained the trailing of Button 1 to the leading of Button 2 plus 100px, and the leading of Button 3 to the trailing of Button 2 plus 100px. Here's how the constraints are listed:

I'm not sure why this isn't working for you -- you didn't give us any information about how your attempt failed. The other methods you listed should also work. For example, you can certainly put the buttons inside a view and center the view in the safe area or main view.

If you want the spacing to be proportional to the width of the screen, you can use the multiplier field of the constraints. For example, delete the horizontal spacing constraint between Button 1 and Button 2, and then create a new one that constrains the centerX of Button 1 to centerX of Button 2. Next, select the constraint that you just created and set it's multiplier field to, say, 0.5. You can do the same for Button 3, but set the multiplier to 1.5. Now you'll have Button 2 centered in the safe area, and the other two buttons placed half way between the edge and center of the safe area, regardless of the screen dimensions. You can change the values to get different spacing, of course.

Upvotes: 1

Related Questions