iOS 系统提供了两种项目入口,一个是Main.storyboard,一个是UIScene。
- Swift纯代码构建Window
- Swift纯代码构建项目
Main.storyboard
创建一新的项目,默认项目入口是Main.storyboard,除非手动将Main.storyboard文件删除,改为纯代码入口。
Main.storyboard的设置:TARGETS -> General -> Development Info
如果是使用storyboard,即故事版开发的话,这里需要选择Main.storyboard。
UIScene
- 删除项目中的Main.storyboard到废纸篓…
2)将TARGETS -> General -> Development Info 的Main Interface设置为空。
- 找到项目里的plist文件,删除Main.storyboard的相关配置。注意,这一点很重要,当将Main Interface设置为空后,项目不会自动删除这里的配置,所以需要手动删除。
4)代码创建Window并显示
纯代码创建Window的正确姿势如下:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
if #available(iOS 13.0, *) {
window = UIWindow(windowScene: scene as! UIWindowScene)
} else {
window = UIWindow(frame: UIScreen.main.bounds)
}
window?.backgroundColor = UIColor.white
window?.frame = UIScreen.main.bounds
let mainVC = MainViewController()
let nav = ENNavigationController(rootViewController: mainVC)
window?.rootViewController = nav
window?.makeKeyAndVisible()
guard let _ = (scene as? UIWindowScene) else { return }
}
需要在SceneDelegate中实例化一个Window对象,并将其绑定到scene上并显示出来。AppDelegate不用添加任何代码(iOS 13之后AppDelegate和SceneDelegate分开为两个类)。
报错处理
- 找不到Main.Storyboard闪退
这是因为删除了Main.Storyboard,设置了程序入口不是Main.Storyboard。但是未删除plist文件中对应的配置导致的。
- Window黑屏
创建的Window黑屏,使用Xcode的查看界面元素的功能看了一下屏幕上面什么都没有。
原因是Window未绑定到scene上,所以scene上是个空,什么都没有,window没放置上去。
创建Window的正确方式是:
if #available(iOS 13.0, *) {
window = UIWindow(windowScene: scene as! UIWindowScene)
} else {
window = UIWindow(frame: UIScreen.main.bounds)
}