user3783005 user3783005 - 7 days ago 5
iOS Question

Adding constraints programmatically in objective-c

I need to add to a UIButton some constraints programmatically.
I need it to have Centre Horizontally to superview, Centre Vertically to superview, Aspect ratio to superview and Aspect Ratio to self.

Can anyone help me please ?

Thank you.

Answer

I'll get the ball rolling for you so you can see the general idea, otherwise use the documentation as provided by Larme.

Add the constraint in your superview (probably your view controller).

NSLayoutConstraint *centreHorizontallyConstraint = [NSLayoutConstraint
                                      constraintWithItem:self.uiButton
                                      attribute:NSLayoutAttributeCenterX
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeCenterX
                                      multiplier:1.0
                                      constant:0];

[self.view addConstraint:centreHorizontallyConstraint];

So as you can see we are saying constraint the centre x attribute of UIButton too the centre x attribute of the View Controllers view with no additional offsets (multiplier set to 1.0 and constant 0).

Make sure you add it to your view controller's view not the button because the button has not been laid out at this point and therefore you cannot add a constraint to it! (Please someone correct me if I'm wrong here). I add my constraints in the viewDidLoad method.