David Robertson
David Robertson

Reputation: 1581

Position uibuttons with auto-layout Swift

I have an uiview with two uibuttons.
The issue is - i cannot understand how to use auto-layout constraints in order to position them the following way enter image description here

Thank you in advance for any insights!

Upvotes: 1

Views: 198

Answers (2)

Szymon Kuczur
Szymon Kuczur

Reputation: 5821

If you don't want to reset the constraints you can try to make the spacing constraints like this:

self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: button1, attribute: NSLayoutAttribute.CenterX, multiplier: 0.275, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: button2, attribute: NSLayoutAttribute.CenterX, multiplier: 0.625, constant: 0))

Note that the order of views is reversed.

I've used it successfully with IB, should work from code.

Upvotes: 0

Ishan Handa
Ishan Handa

Reputation: 2281

Try something like this:

   //Individual button Width
    self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 0.25, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: button2, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 0.25, constant: 0))

    //Button1 left spacing
    self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: self.view.frame.size.width * 0.15))

    //Button2 Right Spacing
    self.view.addConstraint(NSLayoutConstraint(item: button2, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -self.view.frame.size.width * 0.15))

    //Y placement
    self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: button1, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: button2, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))

Also, you will need to reset the constraints on rotation as self.view.frame.size.width will change. It has been used to calculate the constraint constants.

Upvotes: 1

Related Questions