senty
senty

Reputation: 12857

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

self.view.addSubview(myButton1)
self.view.addSubview(myButton2)

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?

Upvotes: 1

Views: 41

Answers (1)

the_critic
the_critic

Reputation: 12820

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.

Upvotes: 0

Related Questions