是否可以迁移旧的Xcode项目以使用SwiftUI?

时间:2019-06-09 14:36:25

标签: ios swift xcode swiftui

我有一个使用Main.sotyboard用Xcode 10制作的应用程序,想将其迁移到使用Apple的新框架:SwiftUI。
已经可以了吗?

我已经尝试在UIApplicationSceneManifest中添加Info.plist键,我将AppDelegate.swift更改为使用场景,创建了SceneDelegate.swift,即使这样我也不能< / p>

3 个答案:

答案 0 :(得分:4)

我假设您正在使用Xcode 11 Beta和macOS MojaveCatalina

随着plist中的更改,您必须在应用程序委托中添加UISceneSession生命周期函数。

func application(_ application: UIApplication,
                 configurationForConnecting connectingSceneSession: UISceneSession,
                 options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    // The name must match the one in the Info.plist
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {

}

此外,您需要确保在window中正确创建了SceneDelegate

func scene(_ scene: UIScene, 
           willConnectTo session: UISceneSession, 
           options connectionOptions: UIScene.ConnectionOptions) {

    let window = UIWindow(frame: UIScreen.main.bounds)
    window.rootViewController = UIHostingController(rootView: ContentView())
    self.window = window
    window.makeKeyAndVisible()
}

其中ContentView是您要显示的主要SwiftUI视图。

P.S。确保plist指定$(PRODUCT_MODULE_NAME).SceneDelegate作为委托类名称,并且场景委托称为SceneDelegate

示例:

enter image description here

如果您使用的是Catalina,则可以在目标的构建设置中启用Previews

构建选项->启用预览


附录I

确保从信息列表中删除 Storyboard 键和该you're targeting iOS 13

enter image description here

enter image description here


附录II

清理Derived Data,正如评论中的许多开发人员所建议的那样。

答案 1 :(得分:2)

这是一个正确的小改动

SceneDelegate.swift中替换

let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()

使用

if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()

}

来自HERE

答案 2 :(得分:0)

我的解决方案却有所不同。就我而言,我已经准备就绪,但是当代码尝试加载UISceneConfiguration时,它无法加载Info.plist中的配置,并给了我一个辅助窗口配置,而没有设置场景委托。如果我从调试控制台要求正确的配置,它将按预期加载。我很困惑。

我仔细检查了所有内容,并在这里尝试了所有建议,但没有一个起作用。最后,我在模拟器上做了'硬件'-'擦除所有内容和设置...',就解决了它。

我的猜测是,因为我一直在模拟器上运行该应用程序的SWIFTUI之前版本,所以其中的某些原因导致SwiftUI版本的行为有所不同。

相关问题