5

I want to execute code before view appears but viewDidLoad is getting called before viewWillAppear. Why is it so??

Ajinkya Patil
  • 5,518
  • 4
  • 20
  • 22

3 Answers3

7

ViewDidLoad is called when the view is loaded in to memory. i.e if you are using storyboard, the app has unarchived the view and loaded it into memory(not yet on screen).

When the app is ready to load the view on the screen it will call the viewWillAppear method.

In your case, if you want to execute code before the view appears on screen, you could add it in either viewDidLoad or viewWillAppear.

TheAppMentor
  • 1,091
  • 7
  • 14
0

Because the view needs to load into memory before it can be displayed. You need to read further about the view lifecycle. Check this link.

Only after the view and it's elements are loaded into memory, the view is painted on screen and viewWillAppear and viewDidAppear is called respectively.

If you need to execute code before view appears you need to use the viewWillAppear method.

mohonish
  • 1,396
  • 1
  • 9
  • 21
0

I just wanted to provide some more information, maybe it will help you. If you use constraints you may look on:

- viewDidLayoutSubviews()

Called to notify the view controller that its view has just laid out its subviews.

So it will be called after your constraints applied.

katleta3000
  • 2,484
  • 1
  • 18
  • 23