Why is self.view.subviews an empty array in viewDidLoad?

I created a group of user interface elements using Interface Builder and connected them to my ViewController using IBOutlets.

However, when I try to iterate through self.view.subviews in my ViewController's viewDidLoad method, I find that the subviews array is empty.

  • ViewController.xib :

     UIView | - UILabel - UIButton - // ... more stuff - UIToolbar 
  • ViewController.m :

     #import "ViewController.h" @interface ViewController () // Interface elements @property IBOutlet UILabel *titleLabel; @property IBOutlet UIButton *button1; // ... etc @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // BREAK_POINT // ... code to wire up the UIButtons to dynamically created objects } 
  • Debugger output in BREAK_POINT :

     (lldb) po self.view <UIView: 0x7fa7897e2140; frame = (0 0; 600 600); autoresize = W+H; layer = <CALayer: 0x7fa7897e2210>> (lldb) po self.view.subviews <__NSArrayI 0x7fa789713500>( ) (lldb) po [self.view.subviews count]; nil (lldb) po self.button1 <UIButton: 0x7fa78955ea70; frame = (-23 -15; 46 30); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x7fa7897663d0>> 

Any ideas why self.views.subviews is empty when explicitly UIButtons etc. have been initialized and correctly connected to IBOutlets?


Edit 1: I renamed "MainView.xib" to "ViewController.xib" and removed the loadView implementation in my ViewController.m , and I still see the behavior of self.view.subviews .

+6
source share
3 answers

Try to do it in

 - (void)viewDidLayoutSubviews{ } 

This method is called after loading all subzones. Hope this helps you :)

+4
source

I believe this may be due to how you load the view. On viewControllers, there is no need to use loadView or NSBundle to load the Nib if your nib and your VC are correctly connected to IB.

Also, if you name yours anything as a ViewController, the designated init will load it correctly for you. If you use loadView, you need to load the entire view tree yourself, not just the main view.

See link: iPhone SDK: what is the difference between loadView and viewDidLoad?

0
source

What if you move the installation code to viewWillAppear ?

0
source

Source: https://habr.com/ru/post/978726/


All Articles