Initialize a view with a xib

风格不统一 提交于 2020-01-01 19:45:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!