//找window的三種方法
UIWindow *window1 = [UIApplication sharedApplication].keyWindow;
UIWindow *window2 = [UIApplication sharedApplication]windows[0];
UIWindow *window3 = [UIApplication sharedApplication].delegate.window;
- (void)viewDidLoad {
//self本類(NowViewController)的對(duì)象
//super父類(UIViewController)的對(duì)象
//先加載父類視圖,確保子類視圖順利加載
[super viewDidLoad];
//視圖控制器在創(chuàng)建時(shí)會(huì)自動(dòng)生成一個(gè)view,作為視圖控制器的一個(gè)自帶屬性
//設(shè)置背景顏色
self.view.backgroundColor= [UIColor blueColor];
//在viewDidLoad方法中寫代碼
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 150, 100)];
label.text = @"viewController";
[self.view addSubview:label];
[self findWindow];
}
//系統(tǒng)的觸摸方法,當(dāng)手指觸摸到屏幕時(shí)調(diào)用
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
//1.導(dǎo)入頭文件
//2.創(chuàng)建視圖控制器對(duì)象
NowViewController *vc = [[NowViewController alloc] init];
//3.找window,不能重新創(chuàng)建window,因?yàn)橐粋€(gè)只能有一個(gè)window
UIWindow *window = self.view.window;
//4.設(shè)置為window的根視圖控制器
window.rootViewController= vc;
//上一句代碼把window的根視圖控制器換掉了,所以現(xiàn)在self.view已經(jīng)不在window上了,所以用self.view.window找不到window
//[self findWindow];
}
//找window
- (void)findWindow {
//方法一(不確定):
UIWindow *window1 =self.view.window;
//方法二(常用):
UIWindow *window2 = [UIApplication sharedApplication].keyWindow;
// UIWindow? *window2 = [[UIApplication sharedApplication] keyWindow];
//方法三:
UIWindow *window3 = [UIApplication sharedApplication].windows[0];
//方法四(最安全):
//找到應(yīng)用程序
UIApplication *app = [UIApplication sharedApplication];
//UIWindow *window4 = [UIApplication sharedApplication];
//找到應(yīng)用程序的入口類
AppDelegate *delegate = app.delegate;
//找到入口類中的屬性window
UIWindow *window4 = delegate.window;
NSLog(@"window1 = %@",window1);
NSLog(@"window2 = %@",window2);
NSLog(@"window3 = %@",window3);
NSLog(@"window4 = %@",window4);
}