Moving views with constraints

Yes, no issue when you change the constants. The thing here is that you have to set your constraint appropriately.

Let’s consider an example.

I have a UIView in Storyboard and I would like to change its width. Its default width is 1024.

After some animation, We will change it’s width to 900.

Follow steps below to achieve this:

  1. Select UIView in which we want to update constraints. Here we need to update width, So we will add a constraint for width.

enter image description here

  1. Now we can see new constraint added to UIView.

enter image description here

  1. Click on that constraint. It will show constraint properties. Here now we want to decrease width from 1024 to 900, So that in constraint property change Relation property to Less Than or Equal. Similarly, if you like to increase width from 1024 then Relation will be Greater Than or Equal.

enter image description here

  1. Now create an IBOutlet variable for NSLayoutConstraint and connect it with above width constraint.

  2. Change width constant

Swift 5.0

@IBOutlet weak var viewWidthConstraint : NSLayoutConstraint!

func reduceWidth() {
    // Reduce width of view.
    UIView.animate(withDuration: 0.35, animations: { () -> Void in
        self.viewWidthConstraint.constant = 900
        self.view.layoutIfNeeded()
    })
}

func normalWidth() {
    // Change to the default width of view.
    UIView.animate(withDuration: 0.35, animations: { () -> Void in
        self.viewWidthConstraint.constant = 1024
        self.view.layoutIfNeeded()
    })
}

Objective C

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

- (void) reduceWidth {
    // Reduce width of view.
    [UIView animateWithDuration:0.35f animations:^{
        self.viewWidthConstraint.constant = 900;
        [self.view layoutIfNeeded];
    }];
}

- (void) normalWidth {
    // Change to default width of view.
    [UIView animateWithDuration:0.35f animations:^{
        self.viewWidthConstraint.constant = 1024;
        [self.view layoutIfNeeded];
    }];
}

Leave a Comment