Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When the autolayout constraints set frames during view controller life cycle?

I have used autolayout constraints from storyboard. However in some cases, I want to calculate dynamic height of subview. I code this in viewDidAppear(), it works fine because this method is called after all view frames are set by layout constraints. The problem here is that I can see the frame set by constraints for half a second. And then the code reframes the view.

I came to know about viewDidLayout() which is called after constraints has set the frame so I can change. But it doesn't work. It is like this method is called before constraints are used.

like image 242
Hiren Prajapati Avatar asked Mar 21 '16 07:03

Hiren Prajapati


2 Answers

The viewDidAppear method is called at the end of the view life cycle. So if you change the constraints here, it will always be visible.

If the change you want to do is a one time event, then you may do so in the method viewWillAppear. But this won't always help because the view drawing may not always be finished by this time. So a better option is to place the code in viewWillLayoutSubviews or viewDidLayoutSubviews.

NOTE: viewWillLayoutSubviews or viewDidLayoutSubviews will be called multiple times in a view's life cycle, such as orientation change or moving in and out of another view or any frame change for that matter.
If the code change you want to put here is a one time event, then please make sure to use flags.

eg:-

- (void)viewWillLayoutSubviews {    
    if(firstTime) {
        // put your constraint change code here.
    }
}

Hope this helps! :)

like image 151
GoGreen Avatar answered Oct 27 '22 15:10

GoGreen


As name suggests, viewDidLayoutSubviews is called when the view of your viewController has just finished its laying out and you can assume that at that dynamic height your views are in their correct places/frames according to your autolayout constraints.

Swift :

    override func viewDidLayoutSubviews() {
       // Set your constraint here
    }

Objective C :

   -(void)viewDidLayoutSubviews {
   // Set your constraint here
   }
like image 24
Anil Kukadeja Avatar answered Oct 27 '22 17:10

Anil Kukadeja