當(dāng)前開發(fā)使用的XCode的版本是13.2創(chuàng)建的SwiftUI的項(xiàng)目厘惦。默認(rèn)配制的是iOS15.0,但是項(xiàng)目要求是最低兼容iOS13.0卡骂,于是在Deployment Info中選擇iOS13就可以了缝左。當(dāng)你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) {
}
}
到此制市,適配代碼已經(jīng)完成。運(yùn)行一下,會發(fā)現(xiàn)啟動后是黑屏。因?yàn)槲覀冞€需要在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打開孵坚,則自己手動添加一下扛伍,添加的效果如下:
至此再次運(yùn)行,在iOS13系統(tǒng)的手機(jī)或模擬器逆航,就可以正常使用了