没有xib文件创建
- (void)viewLoad {
//1 view为空(没有xib文件)
//2 调用view的get方法时
//get方法推测
// -(UIView *)view {
// if (_view == nil) {
// [self viewLoad];
// [self viewDidLoad];
// }
// }
UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.view = view;
}
有xib文件时创建
-(void)viewLoad {
//获取xib路径
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"RootViewController" ofType:@"nib"];
if (filePath) {
//有,拿出放到数组再取出
NSArray *array = [[NSBundle mainBundle]loadNibNamed:@"RootViewController" owner:nil options:nil];
self.view = [array lastObject];
}else{
//没有就创建一个view
UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.view = view;
}
}
有其他xib文件时创建
先把view.xib文件与ViewController类连接
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//window的创建
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//设置window的颜色
self.window.backgroundColor = [UIColor whiteColor];
//设置self.window为keyWindows并显示
[self.window makeKeyAndVisible];
ViewController *viewController = [[ViewController alloc]initWithNibName:@"View" bundle:[NSBundle mainBundle]];
self.window.rootViewController = viewController;
return YES;
}
@end
#import "ViewController.h"
#import "ViewController.h"
@implementation ViewController
-(void)viewLoad {
//获取xib文件名字
NSString *fileName = self.nibName ? self.nibName : @"ViewController";
//获取xib文件资源包
NSBundle *bundle = self.nibBundle ? self.nibBundle : [NSBundle mainBundle];
//获取xib文件路径
NSString *filePath = [bundle pathForResource:fileName ofType:@"nib"];
if (filePath) {
//若有,就取出
NSArray *array = [bundle loadNibNamed:fileName owner:nil options:nil];
self.view = [array lastObject];
}else{
//没有就创建一个view
UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
//view.backgroundColor = [UIColor orangeColor];
self.view = view;
}
}
@end