How to update constraints programmatically?

10,372

Solution 1

create an IBOutlet in your viewController.h file :

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nameButtonVerticalConstraint;

now connect it with the concerned autolayout constraint :

enter image description here

Now you can simply change the constraint like this :

self.nameButtonVerticalConstraint.constant=25;

And if you want smoother transitions, you can put it inside an animation block :

[UIView animateWithDuration:1.2 delay:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    self.nameButtonVerticalConstraint.constant=50;
    [self.view layoutIfNeeded];
} completion:nil];

EDIT : here's an excerpt from this article

If other constraints will be affected because of the update to the constraint above, the following must also be called:

[viewForUpdate setNeedsUpdateConstraints];

Now, animate yout view by calling layoutIfNeeded inside your animation block.

Solution 2

Try myConstraintOutlet.constant = newValue;

Solution 3

You can update the constant property of the layout constraint.

Share:
10,372

Related videos on Youtube

Nik
Author by

Nik

Updated on June 04, 2022

Comments

  • Nik
    Nik almost 2 years

    I want to update constraints programmatically in code. I have added them in storyboard controller. I made IBOutlet for the constraints and connected them. I added values in updateViewConstrains() but it isn't working:

    func updateViewConstraints() {
        centerYConstraint.constant = 60
    
        super.updateViewConstraints()
    }
    
    • Wain
      Wain almost 9 years
      Show your code, what specifically doesn't work?
    • Nik
      Nik almost 9 years
      override func updateViewConstraints() { centerYConstraint.constant = 60 super.updateViewConstraints() }