Swift 纯代码创建项目

iOS 系统提供了两种项目入口,一个是Main.storyboard,一个是UIScene。

  • Swift纯代码构建Window
  • Swift纯代码构建项目

Main.storyboard

创建一新的项目,默认项目入口是Main.storyboard,除非手动将Main.storyboard文件删除,改为纯代码入口。

Main.storyboard的设置:TARGETS -> General -> Development Info
在这里插入图片描述
如果是使用storyboard,即故事版开发的话,这里需要选择Main.storyboard。

UIScene

  1. 删除项目中的Main.storyboard到废纸篓…
    2)将TARGETS -> General -> Development Info 的Main Interface设置为空。

在这里插入图片描述

  1. 找到项目里的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分开为两个类)。

报错处理

  1. 找不到Main.Storyboard闪退

在这里插入图片描述

这是因为删除了Main.Storyboard,设置了程序入口不是Main.Storyboard。但是未删除plist文件中对应的配置导致的。

  1. 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)
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Morris_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值