UISceneDelegate
在
Xcode11
中新建项目,发现从iOS13
开始,AppDelegate
中不再管理Window
,而是将功能迁移到了SceneDelegate
中。-
首先看一下
info.plist
的变化
enable Multipe Windows
--- 是否允许分屏Scene Configuratiton
--- 屏幕配置项Application Session Role
--- 程序屏幕配置规则(为每个Scene
指定规则)Configuration Name
--- 配置名称Delegate Class Name
--- 代理类名称Storyboard Name
---Storyboard
名称
- 根据上面配置,我们可以解读为,创建项目时,系统默认为我们做了设置,一个名为
Default Configuratiton
的默认配置,代理类名称为SceneDelegate
,入口名为Main
的Storyboard
, -
AppDelegate
中代码如下
#pragma mark - UISceneSession lifecycle
- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}
那么问题来了,想要自定义Window
,不通过Storyboard
创建,该如何操作?
在iOS13
及以上系统
- 如果继续使用
SceneDelegate
,需要将info.plist
中的Storyboard Name
选项删除(即不指定Storyboard
) -
SceneDelegate
中代码修改如下:
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
if (@available(ios 13, *)) {
if (scene) {
self.window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];
self.window.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc]init]];
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
}
}
}
低于iOS13
的系统
- 删除
info.plist
文件中的Application Scene Manifest
选项 - 删除
SceneDelegate
文件 - 删除
AppDelegate
中的SceneDelegate
方法 -
AppDelegate.h
中添加
@property (strong, nonatomic) UIWindow *window;
-
AppDelegate
修改代码如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
ViewController * vc = [[ViewController alloc]init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
return YES;
}