How to change constraints programmatically that is added from storyboard?
Asked Answered
M

1

34

I have one screen. It will display like below

enter image description here

Now When User clicked I have an Account and Password(button) it will display like below

enter image description here

I want to move both views accordingly I added constraints using storyboard.Now need to change constraints from programming..

Memento answered 14/11, 2016 at 7:16 Comment(1)
Just create an outlet of the constraint you want to change like you create outlet of UIButton or UILabel.Inly
M
58

You need to create an IBOutlet of your constraint.
enter image description here

Then you set the constant value of your constraint in code:

labelWidthConstraint.constant = newValue

If you want it animated you can do something like this:

Swift

labelWidthConstraint.constant = newValue
UIView.animate(withDuration: 0.3, animations: { 
    self.view.layoutIfNeeded()
})

Objective-C

self.labelWidthConstraint.constant = newValue;
[UIView animateWithDuration:0.3 animations:^{        
    [self.view layoutIfNeeded];
}];
Midis answered 14/11, 2016 at 8:20 Comment(4)
You should not call layoutSubviews()(see docs). Use layoutIfNeeded() instead.Cain
Nilam Pari, I updated the answer to contain an Objective-C example.Midis
Also, for animation, you don't need the constant to be set inside animation block. Put it outside of the animation block, so animation block has layoutIfNeeded method only.Vietnamese
Would be nice to show example that doesn't use hard coded values - how does the UI look different on a 4s in comparison to a 7s plus?Jehol

© 2022 - 2024 — McMap. All rights reserved.