iOS - 建立UIWindow,ios建立uiwindow
iOS程式啟動完畢後,建立的第一個試圖控制項就是UIWindow,接著建立控制器的view,最後將控制器的view添加到UIWindow上
APPdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // 視窗注意點:1.不要被銷毀,需要弄一個強引用 2.必須視窗的尺寸 // 1.建立視窗對象 self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor yellowColor]; // 2.建立視窗的根控制器,並且賦值 UIViewController *rootVc = [[UIViewController alloc] init]; rootVc.view.backgroundColor = [UIColor greenColor]; self.window.rootViewController = rootVc; // 3.顯示視窗 [self.window makeKeyAndVisible]; return YES;}
鍵盤和狀態列都是視窗
UITextField *text = [[UITextField alloc] init];[text becomeFirstResponder];[self.window addSubview:text];
視窗層級UIWindowLevelNormalUIWindowLevelStatusBarUIWindowLevelAlert
alert最大,層級可以加減
通過storyboard載入控制器
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // 1. 建立視窗 self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; // 2.載入main.storyboard // name:storyboard名稱不需要尾碼 UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; // 載入storyboard控制器 // 預設載入箭頭指向的控制器 //UIViewController *vc = [storyboard instantiateInitialViewController]; // 通過標識符載入控制器 UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"blue"]; // 設定視窗的根控制器 self.window.rootViewController = vc; // 3.顯示視窗 [self.window makeKeyAndVisible]; return YES;}
通過xib建立控制器
// xib載入控制器步驟// xib必須有view去描述控制器// xib中哪個view描述控制器view,必須連線// 讓xib和控制器產生連線,告訴xib是用來描述控制器self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];ViewController *vc = [[ViewController alloc] initWithNibName:@"vc" bundle:nil]; self.window.rootViewController = vc;[self.window makeKeyAndVisible];
loadview方法載入控制器
底層實現:判斷下有沒有指定的storyboard,如果有,就會建立storyboard描述的控制器的view,如果沒有就會建立一個空的view
// 作用:載入控制器的view,調用時間:當控制器的view第一次使用的時候調用// BGView是新建立的繼承於UIView的對象- (void)loadView{ BGView *view = [[BGView alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.view = view; self.view.backgroundColor = [UIColor redColor];}