1. 直接加载xib中的UIView
创建一个View1.xib
直接加载Xib中view获取View1代码:
NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"View1"
owner:nil
options:nil];
UIView *view1 = [views lastObject];
2. 通过Owner建立变量关联
File's Owner为NSObject
类型,可以使用UIViewController
,也可一创建一个继承NSObject
的子类ViewFileOwner
,以创建ViewFileOwner
为例。
在ViewFileOnwer
中声明IBOutLet的关联变量view
:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface ViewFileOwner : NSObject
@property (weak, nonatomic) IBOutlet UIView *view;
+ (id)viewFromNibNamed:(NSString *)nibName;
@end
#import "ViewFileOwner.h"
@implementation ViewFileOwner
+ (id)viewFromNibNamed:(NSString *)nibName
{
ViewFileOwner *fileOwner = [ViewFileOwner new];
[[NSBundle mainBundle] loadNibNamed:nibName
owner:fileOwner
options:nil];
return fileOwner.view;
}
@end
创建一个YZOwnerView.xib
,File's Owner设为ViewFileOnwer
,并建立关联,如下:
获取Xib View代码:
ViewFileOwner *fileOwner = [ViewFileOwner new];
[[NSBundle mainBundle] loadNibNamed:@"YZOwnerView"
owner:fileOwner
options:nil];
UIView *view = fileOwner.view;
可以建立UIView的Category,封装方法,简化添加代码
#import <UIKit/UIKit.h>
@interface UIView (XibHelper)
+ (id)loadFromNibName:(NSString *)nibName;
+ (id)loadFromNib;
@end
#import "UIView+XibHelper.h"
#import "ViewFileOwner.h"
@implementation UIView (XibHelper)
+ (id)loadFromNibName:(NSString *)nibName
{
return [ViewFileOwner viewFromNibNamed:nibName];
}
+ (id)loadFromNib
{
return [[self class] loadFromNibName:NSStringFromClass([self class])];
}
@end
可直接这样调用:UIView *view = [UIView loadFromNibName:@"YZOwnerView"];
如果建立UIView的子类YZView
关联了Xib中View,可直接调用:YZView *view = [YZView loadFromNib];
UIView子类关联
参考文章:iOS开发之多XIB之间相互关联
网友评论