33

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.

Max Desiatov
  • 5,087
  • 3
  • 48
  • 56
Michitaka
  • 550
  • 1
  • 4
  • 7

2 Answers2

30

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.

jvarela
  • 3,744
  • 1
  • 22
  • 43
Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
  • Could you explain a little more on what is setNeedsLayout & setNeedsDisplayInRect? I couldn't understand the linked page.. – Allister Bah Jun 02 '15 at 08:20
  • Check [this comment](http://stackoverflow.com/a/13542580) for a good explanation about `setNeedsLayout` – shehanrg Feb 03 '16 at 15:31
1

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.

Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78