UIWindow

一、UIWindow的作用?

  • A UIScreen object that identifies physical screen connected to the device.
  • A UIWindow object that provides drawing support for the screen.
  • A set of UIView objects to perform the drawing. These objects are attached to the window and draw their contents when the window asks them to.(不太好翻译)

二、系统如何自动创建Window和window的根控制器?

  • 在main函数中,UIApplicationMain会加在info.plist文件,并判断有没有指定Main Interface, 系统默认的Main Interface指向Main.storyboard,然后自动创建window,并加在Main.storyboard中的启动控制器(initial View Controller)。

三、如何用代码方式创建window和window的根控制器?

1.首先删除Main Interface中的内容

删除Main Interface指定的入口

2.AppDelegate中代码创建如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];  
    UIViewController *VC = [[UIViewController alloc] init];
    // VC.view.backgroundColor = [UIColor orangeColor];  
    self.window.rootViewController = VC;
    [self.window makeKeyAndVisible];
    return YES;
}

四、如何从自定义的storyboard中创建window的根控制器

1.创建一个storyboard, 命名为"XJStoryboard"

创建storyboard

2.storyboard中拖一个viewController进去,并设置为这个storyboard的initial viewController

3.AppDelegate中代码创建如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"XJStoryboard" bundle:nil];   
    self.window.rootViewController = storyboard.instantiateInitialViewController;  
    [self.window makeKeyAndVisible]; 
    return YES;
}
  • 注意:上面的代码其实不写也可以,直接在Main Interface 中指定你需要加载的storyboard,系统会自动创建window和根控制器。

五、如何从自定义的xib中创建window的根控制器

1.xib的创建


xib文件的创建

2.上面创建的是一个空的xib,现在拖一个UIView进去,设置这个xib的File's Owner为ViewController,并把ViewController的View指向刚刚拖进区的UIView,如下图所示,

关联ViewController
File's Owner的view 连线到刚刚拖进去的UIView

3.代码部分

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    // 这里的ViewController借用了工程创建时,Xcode自动创建的类
    // 这里完全可以直接创建一个自定义的带xib的Controller
    // 这里主要展示如何自己创建一个空的xib,然后关联已存在的类
    UIViewController *VC = [[ViewController alloc] initWithNibName:@"XJXib" bundle:nil];  
    self.window.rootViewController = VC;
    [self.window makeKeyAndVisible];
    return YES;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容