- (id)init{
if (self = [super init]) {
NSLog(@"%@",self.view);
}
return self;
}
- (UIView*)view{
//若view存在,则返回
if ([self valueForKey:@"_view"]) {
return [self valueForKey:@"_view"];
}
//若不存在,则先调用loadView,再调用viewDidLoad,再返回view
[self loadView];
[self viewDidLoad];
return [self valueForKey:@"_view"];
}
- (void)loadView{
//判断xib文件是否存在
NSFileManager *manager = [NSFileManager defaultManager];
//xib文件路径(后缀名是nib)
NSString *path = [[NSBundle mainBundle] pathForResource:NSStringFromClass([self class]) ofType:@"nib"];
if ([manager fileExistsAtPath:path]) {
//通过xib文件加载视图
//loadNib...可以返回一个xib文件中视图元素数组(view,view1)
//owner参数必须要写,如果不写,则不会对声明IBOutlet的变量赋值
[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
return;
}
//若不存在,则创建一个新视图
UIView *myView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
myView.backgroundColor = [UIColor redColor];
[self setView:myView];
}
- (void)viewDidLoad {
[super viewDidLoad];
}