Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep UIButtons centered using autolayout in storyboard

I have two buttons contained within a view (to be precise, a UITableView footer):

enter image description here

I would like to keep the buttons centered (with the gap in-between) regardless of the width of the superview (which will increase, for example, if the device is rotated to portrait orientation).

Is there a way to define these autolayout constraints purely in the storyboard, or will I need to use NSLayoutConstraints in code?

like image 228
Skoota Avatar asked Apr 15 '14 03:04

Skoota


People also ask

How Auto Layout work in ios?

Auto Layout defines your user interface using a series of constraints. Constraints typically represent a relationship between two views. Auto Layout then calculates the size and location of each view based on these constraints. This produces layouts that dynamically respond to both internal and external changes.

What is Autolayout in swift?

Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.


1 Answers

You can achieve that by adding a constraint for each button to align the leading/trailing to the center of the container view, plus some separation between them.

How to do it:

  • For the left side button, add a constraint between the button and superview to center it horizontally.

  • Edit the constraint and change the "Second Item" attribute to be button1.trailing, and set a constant of 10 (or whatever distance you want between the right border of the button and the center of the screen).

alignmentConstraint1

  • For the right side button, add a constraint between the button and superview to center it horizontally.

  • Edit the constraint and change the "Second Item" attribute to be button2.leading and set a constant of -10 (or whatever distance you want between the left border of the button and the center of the screen).

enter image description here

like image 64
Matías R Avatar answered Nov 03 '22 00:11

Matías R