Extracting UI items from xib?
After a litte hunting through the docs I have decided on the following technique using "viewWithTag" to extract sub views from the main root view returned by loadNibNamed:owner:options: To start with I was a little confused as I assumed loadNibNamed:owner:options would return an array containing all my UI items (i.e. labels, buttons etc.) when in fact it seems to return the root view (or root views). Can anyone confirm that I am doing this right, I am just curious if there are other (maybe better) ways to extract and set items from within a xib file?
- (void)loadView {
NSLog(@"HYBRID UI: %s", __PRETTY_FUNCTION__);
NSArray *nibArchive = [[NSBundle mainBundle] loadNibNamed:@"Interface" owner:self options:nil];
NSLog(@"SIZE: %d ARRAY: %@", [nibArchive count], nibArchive);
// UIView
UIView *nibView = [nibArchive lastObject];
[nibView setFrame:[[UIScreen mainScreen] applicationFrame]];
NSLog(@"FRAME: %@", NSStringFromCGRect([nibView frame]));
[self setView: nibView];
// UILabel
UILabel *nibLabel = (UILabel *)[nibView viewWithTag:101];开发者_开发问答
[nibLabel setText:@"FRINGE"];
[nibLabel setTextColor:[UIColor whiteColor]];
// UIImageView
UIImageView *nibImageView = (UIImageView *)[nibView viewWithTag:102];
[nibImageView setBackgroundColor:[UIColor whiteColor]];
}
cheers gary
loadNibNamed:owner:options:
does return an array of all root objects in the NIB. To get to other objects in the hierarchy, you can traverse the hierarchy manually (not a good idea in most cases), use tags as you did or use outlets.
If you declare outlets in your view controller for the view, the label and the image view and connect them in the NIB to the appropriate objects, they will be automatically connected in loadNibNamed:owner:options:
.
PS: Why do you load the NIB manually anyway? Can't you init your view controller with initWithNibName:bundle
and do the rest of the initialization in viewDidLoad
?
It seems like you're making this harder than it needs to be. If you're subclassing UIViewController, just call [super initWithNibName:@"whatever" bundle:nil]
in your init
, then you won't have to call loadNibNamed:owner:options
yourself. And since you're using a nib, you should put your code in viewDidLoad
without implementing loadView
.
In your interface, set up an IBOutlet for the views you are interested in:
@property (nonatomic, retain) IBOutlet UILabel *titleLabel;
In the nib, set the File's Owner class to your UIViewController subclass, and then you can connect the titleLabel to the actual UILabel.
精彩评论