Context:
MainView.xib
: I've laid out my UI elements and painstakingly aligned them perfectly using autolayout. There are a whole bunch of UIButtons, a UILabel and a UIToolbar. The hierarchy is pretty flat like this:UIView // Hooked up to ViewController | - UILabel - UIButton - UIButton - UIButton - ... // more buttons - UIToolbar
ViewController.m
:#import "ViewController.h" @interface ViewController () @property NSArray *_allButtons; // Interface elements @property IBOutlet UILabel *titleLabel; @property IBOutlet UIButton *button1; @property IBOutlet UIButton *button2; // ... lots more buttons @property IBOutlet UIToolbar *toolbar; @end @implementation ViewController - (void)loadView { UIView *mainView = [[[NSBundle mainBundle] loadNibNamed:@"MainView" owner:self options:nil] objectAtIndex:0]; self.view = mainView; } - (void)viewDidLoad { [super viewDidLoad]; // BREAK_POINT // ... code to wire up the UIButtons to dynamically created objects }
Wierd Observation:
I've correctly hooked up my individually created IBOutlet UIButton button<n>
pointers to the UIButtons in the .xib file. And that code works fine.
However, it's a pain to maintain all the buttons individually like this. I could create them all programmatically, but it's much nicer to move them around visually in Interface Builder (now that I've learnt how to use it).
I figured I could remove the IBOutlet connections for the UIButtons, and find them as subviews of the main UIView in MainView.xib, with some code like this in viewDidLoad
:
for (UIView *view in self.view.subviews) {
if( [view isKindOfClass:[UIButton class]]) {
[self._allButtons addObject:view];
}
}
Unfortunately, self._allButtons
was turning out to be an empty array.
So, I brought back the IBOutlet connections, dropped in a break point in viewDidLoad
, and saw this:
(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>>
Which is incredibly strange...that button1
is initialized, but is not a subview of the UIView.