//找window的三种方法
UIWindow *window1 = [UIApplication sharedApplication].keyWindow;
UIWindow *window2 = [UIApplication sharedApplication]windows[0];
UIWindow *window3 = [UIApplication sharedApplication].delegate.window;
- (void)viewDidLoad {
//self本类(NowViewController)的对象
//super父类(UIViewController)的对象
//先加载父类视图,确保子类视图顺利加载
[super viewDidLoad];
//视图控制器在创建时会自动生成一个view,作为视图控制器的一个自带属性
//设置背景颜色
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];
}
//系统的触摸方法,当手指触摸到屏幕时调用
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
//1.导入头文件
//2.创建视图控制器对象
NowViewController *vc = [[NowViewController alloc] init];
//3.找window,不能重新创建window,因为一个只能有一个window
UIWindow *window = self.view.window;
//4.设置为window的根视图控制器
window.rootViewController= vc;
//上一句代码把window的根视图控制器换掉了,所以现在self.view已经不在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];
//方法四(最安全):
//找到应用程序
UIApplication *app = [UIApplication sharedApplication];
//UIWindow *window4 = [UIApplication sharedApplication];
//找到应用程序的入口类
AppDelegate *delegate = app.delegate;
//找到入口类中的属性window
UIWindow *window4 = delegate.window;
NSLog(@"window1 = %@",window1);
NSLog(@"window2 = %@",window2);
NSLog(@"window3 = %@",window3);
NSLog(@"window4 = %@",window4);
}