Tuesday, April 22, 2014

How the XIB resource item connect to IBOutlet or IBAction


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.

2 comments:

  1. I love this. It is soo informative. Are you also searching for cheap assignment help we are the best solution for you. We are best known for delivering the best services to students without having to break the bank

    ReplyDelete
  2. This post is quite informative. I love reading your blogs. Quite helpful. Are you also searching for Academic content writing services we are the best solution for you. We are best known for delivering the best services to students without having to break the bank.

    ReplyDelete