Why is self.view.subviews an empty array in viewDi

2019-02-22 04:53发布

问题:

I've created a bunch of UI elements using Interface Builder and hooked them up 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 at 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 clearly the UIButtons, etc have been initialized and wired up to the IBOutlets correctly?


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

回答1:

Try to do that in

- (void)viewDidLayoutSubviews{


}

This method get called after loading all the subviews. Hope this will help you :)



回答2:

I believe it might be related on the way you load the view. On viewControllers there's no need to use loadView, or NSBundle to loadNib if your nib and your VC are properly linked on IB.

Also if you name your nib as the ViewController, the designated init will load it properly for you. If you use loadView you have to load all the view tree yourself, not only the main view.

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



回答3:

What if you move your setup code to viewWillAppear?