Adding constraints programmatically in Objective-C

I found this tutorial best.

http://www.tutorialspoint.com/ios/ios_auto_layouts.htm

My requirement was to set:

  • Leading Space
  • Top Space
  • fixed Width
  • fixed Height

Adding NSLayoutConstraint with the code below I was able to achieve it

Objective-c

self.btnCoin.translatesAutoresizingMaskIntoConstraints = NO;
/* Leading space to superview */
NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint
                                             constraintWithItem:self.btnCoin attribute:NSLayoutAttributeLeft
                                             relatedBy:NSLayoutRelationEqual toItem:self attribute:
                                             NSLayoutAttributeLeft multiplier:1.0 constant:30];
/* Top space to superview Y*/
NSLayoutConstraint *leftButtonYConstraint = [NSLayoutConstraint
                                             constraintWithItem:self.btnCoin attribute:NSLayoutAttributeTop
                                             relatedBy:NSLayoutRelationEqual toItem:self attribute:
                                             NSLayoutAttributeTop multiplier:1.0f constant:258];
/* Fixed width */
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.btnCoin
                                                                   attribute:NSLayoutAttributeWidth
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:nil
                                                                   attribute:NSLayoutAttributeNotAnAttribute
                                                                  multiplier:1.0
                                                                    constant:35];
/* Fixed Height */
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.btnCoin
                                                                    attribute:NSLayoutAttributeHeight
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:nil
                                                                    attribute:NSLayoutAttributeNotAnAttribute
                                                                   multiplier:1.0
                                                                     constant:12];
/* 4. Add the constraints to button's superview*/
[self addConstraints:@[leftButtonXConstraint, leftButtonYConstraint, widthConstraint, heightConstraint]];

SWIFT:

btnCoin.translatesAutoresizingMaskIntoConstraints = false
// Leading space to superview
let leftButtonXConstraint = NSLayoutConstraint(
    item: btnCoin,
    attribute: .left,
    relatedBy: .equal,
    toItem: self,
    attribute: .left,
    multiplier: 1.0,
    constant: 30)
// Top space to superview Y
let leftButtonYConstraint = NSLayoutConstraint(
    item: btnCoin,
    attribute: .top,
    relatedBy: .equal,
    toItem: self,
    attribute: .top,
    multiplier: 1.0,
    constant: 258)
// Fixed width
let widthConstraint = NSLayoutConstraint(
    item: btnCoin,
    attribute: .width,
    relatedBy: .equal,
    toItem: nil,
    attribute: .notAnAttribute,
    multiplier: 1.0,
    constant: 35)
// Fixed Height
let heightConstraint = NSLayoutConstraint(
    item: btnCoin,
    attribute: .height,
    relatedBy: .equal,
    toItem: nil,
    attribute: .notAnAttribute,
    multiplier: 1.0,
    constant: 12)

In the code above i set left button constraints. Here is the output:

Portrait

Landscape


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.


We have better option available from iOS 9+

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
imageView.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:imageView];

[imageView.widthAnchor constraintEqualToConstant:imageSize.width].active = YES;
[imageView.heightAnchor constraintEqualToConstant:imageSize.height].active = YES;
[imageView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
[imageView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:25].active = YES;

Swift 4

var imageView = UIImageView(frame: CGRect.zero)
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)

imageView.widthAnchor.constraint(equalToConstant: imageSize.width).isActive = true
imageView.heightAnchor.constraint(equalToConstant: imageSize.height).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 25).isActive = true

// OR you can use: NSLayoutConstraint.activate([NSLayoutConstraint]) to activate all at once.

NB: Always add constrains after added the view to view hierarchy.