27

I need to add some constraints to a UIButton programmatically. I need it to have it centred horizontally to superview, centred vertically to superview, aspect ratio to its superview and aspect ratio to self.

Can anyone help me please?

Thank you.

2

3 Answers 3

45

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.

Sign up to request clarification or add additional context in comments.

2 Comments

A good example such as this is worth ten pages of documentation. The developer reference is at times like an exhaustive chemical description of <insert your headache pain reliever drug name here>, when really what you need to know is simple instructions how to take it.
Amen to Ugo's comment.
41

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.

Comments

28

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

2 Comments

what is this mean constant:258,constant:35 etc. how we use this numerical value?
NSLayoutAttributeLeft multiplier:1.0 constant:30]; is control's placement from left edge NSLayoutAttributeTop multiplier:1.0f constant:258]; is control's placement from top.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.