Grouping UIButtons as a Layer and Horizontally Center

I have 2 buttons on the screen where I programatically create and place.

let myButton1 = UIButton()
let myButton2 = UIButton()

let myButton1Frame = CGRectMake(anotherField.origin.x + 20, anotherField.origin.y + 80, 30, 30)
myButton1.frame = myButton1Frame

var myButton2Frame = myButton1Frame
myButton2Frame.origin.x += 130 
myButton2.frame = myButton2Frame


What I tried to achieve visually was...

|        AnotherField      |
|                          |
|     myBtn1     myBtn2    |

What I tried to achieve works okay'ish on Simulator, but I believe there is a smarter way to achieve it with using constraints.

I thought If I can manage to group myButton1 and myButton2, I can just give +y origin the group and then center the buttons horizontally by giving them a distance x from each other (I mean, distance between 2 buttons - Hopefully this makes sense).

What is the proper way to do it? Or is there a better way for me to achieve that?


My suggestion is that you put both buttons into a container view and center that container in your superview.

So it would look something like this:

||   Button1    ||    Button 2  ||

So you'll need to complete these steps:

  • add the view container that will contain the buttons (the "button container")
  • add the two buttons into the aforementioned container
  • add fully satisfying constraints from the buttons to the enclosing container view.
  • add a horizontal center constraint from the container view to the superview (your controller's view for example).

You specified autolayout and layout constraints in your question tags, so I assume you use autolayout (your code does not make use of auto layout or constraints that's why I bring this up).

The constraints (if properly set up between the buttons and container view) should properly size the container view, and once the container view is done layouting, the horizontal constraint to the container's superview will also come into play, effectively centering the container and as a consequence also both of your buttons.

I hope that makes things clear, let me know if you need further assistance or if something remains unclear.

Need Your Help

Acts as Tree gem - Is there any way to make an element have two parents?

ruby-on-rails ruby ruby-on-rails-4 acts-as-taggable-on acts-as-tree

I am using the acts_as_tree gem in order to implement a category list in which a freelancer can select categories and subcategories. "Web design" is one of the subcategories, and it should have two

External memory data structure to replace vector of maps

c++ algorithm memory data-structures stl

I'm doing an iterative computation on a flow network during which I need to record how much each source contributes to the flow on each edge. The flow on any one edge is due to 2% of the sources on