Michitaka
Michitaka

Reputation: 550

Why is viewDidLayoutSubviews called multiple times?

I'm developing iOS Universal App with Swift, using auto layout and support only portrait.

I found UIViewController.viewDidLayoutSubviews called multiple times. Instead, viewDidLoad is only called once on starting up MyApp's UIViewController.

Why is viewDidLayoutSubviews called multiple times? Will constraints on each UIView (UIButtons,UITextFields, etc..) be performed in order?

Any information will be appreciated.

Upvotes: 33

Views: 23990

Answers (2)

Hayley Guillou
Hayley Guillou

Reputation: 3973

LoadView is only called once: when the view needs to be loaded.

LayoutSubviews, however, is called once per run loop on any view that has had setNeedsLayout or setNeedsDisplayInRect called on it - this includes whenever a subview has been added to the view, scrolling, resizing, etc.

Upvotes: 30

Morten Carlsen
Morten Carlsen

Reputation: 39

The best thing to do and this has served me well - is to get in to the habit of adding a log or print statement to methods of which you are unsure

I use this ->

print("Hello From \(NSStringFromSelector(#function))")

or this if inside a View Subclass

Swift.print("Hello From \(NSStringFromSelector(#function))")

It will print the method when it is being called.

Upvotes: 1

Related Questions