The below is a typical code when using xib resource from a IBOutlet property, however, notice the strange thing in headerView property, inside the if block, it just loads the nib file, but not assign the value of _headerView, so how the variable is magically assigned when XIB (nib) resource is loaded?
@interface BNRItemsViewController ()
@property (nonatomic, strong) IBOutlet UIView *headerView;
@end
@implementation BNRItemsViewController
- (UIView *)headerView
{
// If you have not loaded the headerView yet...
if (!_headerView) {
// Load HeaderView.xib
NSArray* arr = [[NSBundle mainBundle] loadNibNamed:@"HeaderView"
owner:self
options:nil];
}
return _headerView;
}
@end
The magic happens with the HeaderView.xib's File Owner settings, in headerview.xib, the file owner is set to BNRItemViewController, in addition, the fileOwner's (i.e BNRItemViewController's headerView property is associated to the UIView control in the xib resource. As a result, when loadNibNamed:owner:options is called, after the resource is loaded into memory, it sets the file owner as self (i.e. currrent BNRItemViewController), and then set the headerView IBOutlet property to the UIView resource item. So the property will be automatically assigned to a loaded uiview instance.
you have now seen that a XIB file can be used any time on any class set to its Files' Owner, any object can load a XIB file manually by sending the message loadNibNamed:owner:options: to the application bundle to associate the resouce with its properties.
Note that a UI control in xib file may also need a delegate to handle its event, this is done by control drag the control to file's Owner, so it specifies whatever object works as file's owner will need to handle the uiview's event.
you have now seen that a XIB file can be used any time on any class set to its Files' Owner, any object can load a XIB file manually by sending the message loadNibNamed:owner:options: to the application bundle to associate the resouce with its properties.
Note that a UI control in xib file may also need a delegate to handle its event, this is done by control drag the control to file's Owner, so it specifies whatever object works as file's owner will need to handle the uiview's event.