18

I modified programmatically one autolayout constraint. It takes effect on one certain view, but other views that are bound with other constraints to that view, do not change their positions. Is there an "updateAllConstraints" method?

1
  • Maybe you coud post a screen of your constraints: the only think I may suppose is that these other views are somehow bounded to other elements by non-stretchable constraints.
    – nikans
    Dec 8, 2013 at 9:17

4 Answers 4

39

Call those two methods on the view you want to be updated:

-setNeedsLayout
-layoutIfNeeded

The first one says to the layout system that this view needs to be laid out, because it has some changes and, everything should be recalculated. The second force the layout system to be run now, layout system is triggered at specific times during runtime, with this method you are saying:"do it now".

4
  • Can i change constrains of an Imageview through UIButton click? If so, How please explain as i am new in this.
    – Sofeda
    May 19, 2016 at 8:57
  • Totally agree with this answer!
    – hamsternik
    Dec 24, 2017 at 15:50
  • 1
    @Sofeda sure you can. In your UIButton's action method you could remove the constraints of the UIImageView with e.g. view.removeConstraints(imageView) and then set new constraints.
    – Baran
    Sep 1, 2018 at 11:44
  • The code given in the answer will also recalculate the constraints even if the view is not attached to the hierarchy
    – RareScrap
    Dec 9, 2020 at 3:18
4

Yes There is a method on UIView called - (void)updateConstraintsIfNeeded

https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/updateConstraintsIfNeeded

However I don't think this is your problem

2

The problem was that constrains were not set up properly, and in this case non of the setNeedsLayout or updateConstraintsIfNeeded can help.

-2

Those of you that come across this topic, and are looking where to find this in the menus.

Best I have found is:

  1. Select the items that you want to "pop" back to your constraints

  2. Top menu: Editor/Update Frames (or/) shortcut: command + option + =

Hopefully this helps

3
  • The question was on how to do it programmatically. Your answer is correct, but unfortunately does not fit that question
    – Taier
    Jun 6, 2018 at 9:30
  • Yes @Taier, I have edited my post to reflect your comment, thank you.
    – CrazyOne
    Apr 10, 2019 at 18:23
  • almost 1 year :)
    – Taier
    Apr 10, 2019 at 23:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.