问题
I want to initialize a view with an xib. That is a UIView. So I have a xib and a UIView subclass with the init code pasted below (initWitFrame nibName). I feed the xib name to the init code from a view controller when creating the view.
SubclassUIView *view = [[SubclassUIView alloc]initWithFrame:self.view.bounds nibName:@"xibName"];
Am I on the right track? So far the contents of the xib does not load with the view.
By the way the main view in the xib is set to be the class type of my UIView subclass.
- (id)initWithFrame:(CGRect)frame nibName:(NSString*)nibName
{
self = [super initWithFrame:frame];
if (self)
{
[[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
[self addSubview:self.view];
}
return self;
}
回答1:
What is returned from the NSBundle is an NSArray (of visual controls, mainly UIViews). Appart from that the code seems right. Have a look at a functioning example:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"TestView"
owner:self
options:nil];
UIView* mainView = (UIView*)[nibViews objectAtIndex:0];
[self addSubview:mainView];
}
return self;
}
回答2:
@Mike M: This behaviour can cause random crashes. Sometimes an NSApplication object will be the firstObject -> crash
Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html
"The order in which the nib-loading code calls the awakeFromNib methods of objects is not guaranteed. In OS X, Cocoa tries to call the awakeFromNib method of File’s Owner last but does not guarantee that behavior. If you need to configure the objects in your nib file further at load time, the most appropriate time to do so is after your nib-loading call returns. At that point, all of the objects are created, initialized, and ready for use."
来源:https://stackoverflow.com/questions/14805217/initialize-a-view-with-a-xib