分享

NIB如何在运行中loadnib文件

 quasiceo 2015-04-22

Loading a Nib file, Programmatically (Objective-C)



If you want to load a Nib file at run time by simply allocating and initializing a View object, then you should take a rather strange approach to how you create your class files. Suppose you have a subclass of UIView called MyView and what you want is to allocate and initialize an instance of MyView but have MyView load its outlets and actions from a Nib file. Well, you will need to do two things:

1) In Interface Builder, change the class name of your View object to MyView.
Posted Image

2) Then you will have to override MyView's initWithFrame method like so:

- (id)initWithFrame:(CGRect)paramFrame
{
   
   
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"MyView"
                                                          owner
:nil
                                                        options
:nil];
   
   
if ([arrayOfViews count] < 1){
       
[self release];
       
return nil;
   
}
   
   
MyView *newView = [[arrayOfViews objectAtIndex:0] retain];
   
[newView setFrame:paramFrame];
   
   
[self release];
   
self = newView;
   
   
return self;
   
}


Then you can go ahead and initialize your view like this:

MyView *myView = [[MyView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:myView];
[myView release];


And here an instance of MyView will get added to the view of a view controller. That simple. I
hope it helps some of you out there :-)


原帖地址
http://answers./topic/2578-loading-a-nib-file-programmatically-objective-c/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多