如何在iOS 14(Xcode 12 Beta)中从UIKit生命周期转换为SwiftUI生命周期

如何在iOS 14(Xcode 12 Beta)中从UIKit生命周期转换为SwiftUI生命周期

问题描述:

我目前正在使用SceneDelegateAppDelegate的SwiftUI应用程序上工作.我想知道如何将生命周期从UIKit转换为SwiftUI,其中存在App结构并使用scenes等.

I am currently working on SwiftUI app in which I am using SceneDelegate and AppDelegate. I would like to know how I can convert the life cycle from UIKit to SwiftUI one where there is an App struct and with scenes etc.

我还想知道如何迎合CoreData和PersistentContainers并将它们注入我们的环境.

Also I would like to know how to cater for CoreData and PersistentContainers and inject these into our environments.

我也曾使用UIApplicationDelegateAdapter注入AppDelegate,但@main给了我错误

Also I have used UIApplicationDelegateAdapter to inject AppDelegate but the @main is giving me error

'main()'仅在iOS 14.0或更高版本中可用

'main()' is only available in iOS 14.0 or newer

我在一开始使用的是@available (iOS 14.0, *):

import SwiftUI

@available(iOS 14.0, *)
@main

struct MyApp: App {

    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

这样做,SceneDelegate代码在哪里.我仍然很困惑这种转换是如何进行的.我还没有看到苹果在他们的会议中谈论这个问题.帮助将不胜感激.

Doing it like this, where does the SceneDelegate code goes. I am still quite confused how this conversion goes. I have not seen Apple talking about this in their sessions or anything. Help will be really appreciated.

在ContentView上设置环境,如下所示:

Set the environment on the ContentView as follows:

import SwiftUI
import CoreData

@main
struct MasterDetailApp: App {
  @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView().environment(\.managedObjectContext, appDelegate.persistentContainer.viewContext)
        }
    }
}