Swift UI

SwiftUI新建项目兼容iOS13.0

2022-02-25  本文已影响0人  ZJL大魔神

当前开发使用的XCode的版本是13.2创建的SwiftUI的项目。默认配制的是iOS15.0,但是项目要求是最低兼容iOS13.0,于是在Deployment Info中选择iOS13就可以了。当你Run一下的时时候,问题就来了:
main()’ is only available in iOS 14.0 or newer

在启动的Scene中会报错,自动生成的方法,只能在iOS14以上的版本使用。于是我们要做一下适配上接上代码

import SwiftUI
import UIKit
@main
struct SwiftUIDemoAppWrapper {
    staticfuncmain() {
        if#available(iOS14.0, *) {
            SwiftUIDemoApp.main()
        }else{
            UIApplicationMain(
                CommandLine.argc,
                CommandLine.unsafeArgv,
                nil,
                NSStringFromClass(SceneDelegate.self))
        }
    }
}

@available(iOS 14.0, *)
struct SwiftUIDemoApp: App {
    varbody:someScene{
        WindowGroup {
            ContentView()
        }
    }
}

其中的SceneDelegate为新建的一个文件,需要在这个文件中配制iOS13的window,代码如下:

import UIKit
import SwiftUI
 
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
    var window: UIWindow?
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: ContentView())
            self.window = window
            window.makeKeyAndVisible()
        }
    }
    
    func sceneDidDisconnect(_ scene: UIScene) {
        
    }
    
    func sceneDidBecomeActive(_ scene: UIScene) {
        
    }
    
    func sceneWillResignActive(_ scene: UIScene) {
        
    }
    
    func sceneWillEnterForeground(_ scene: UIScene) {
        
    }
    
    func sceneDidEnterBackground(_ scene: UIScene) {
        
    }
}

到此,适配代码已经完成。运行一下,会发现启动后是黑屏。因为我们还需要在info.plist文件中配制:
将info文件用Source Code方式打开,添加如下代码:

   <key>UIApplicationSceneManifest</key>
       <dict>
           <key>UIApplicationSupportsMultipleScenes</key>
           <false/>
           <key>UISceneConfigurations</key>
           <dict>
           <key>UIWindowSceneSessionRoleApplication</key>
           <array>
               <dict>
                   <key>UISceneConfigurationName</key>
                   <string>Default Configuration</string>
                   <key>UISceneDelegateClassName</key>
                   <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
               </dict>
           </array>
       </dict>
   </dict>

如果不能用Source Code打开,则自己手动添加一下,添加的效果如下:



至此再次运行,在iOS13系统的手机或模拟器,就可以正常使用了

上一篇下一篇

猜你喜欢

热点阅读