【问题标题】:How to convert from UIKit life cycle to SwiftUI life cycle in iOS 14 (Xcode 12 Beta)iOS 14(Xcode 12 Beta)中如何从UIKit生命周期转换为SwiftUI生命周期
【发布时间】:2020-10-15 03:52:49
【问题描述】:

我目前正在使用 SceneDelegateAppDelegate 开发 SwiftUI 应用程序。我想知道如何将生命周期从UIKit 转换为SwiftUI 一个有App 结构和scenes 等的。

我还想知道如何满足 CoreData 和 PersistentContainers 并将它们注入我们的环境。

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

'main()' 仅适用于 iOS 14.0 或更新版本

我在开头使用@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 代码去哪了。我仍然很困惑这种转换是如何进行的。我还没有看到苹果在他们的会议上谈论这个或任何事情。非常感谢您的帮助。

【问题讨论】:

  • 我认为您必须将部署目标设置为 iOS 14,如果您想很快发布应用程序,您可能不想这样做。

标签: ios swiftui appdelegate xcode12


【解决方案1】:

SceneDelegate 代码在哪里。

@available(iOS 14.0, *)
@main
struct MyApp: App {

    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    @Environment(\.scenePhase) private var scenePhase

    var body: some Scene {
        WindowGroup {         // << this is a scene
          ContentView()
            .onChange(of: scenePhase) { phase in
              switch phase {
                case .active:
                    print(">> your code is here on scene become active")
                case .inactive:
                    print(">> your code is here on become inactive")
                case .background:
                    print(">> your code is here on go in background")
                default:
                    print(">> do something else in future")
             }
          }
        }
    }
}

【讨论】:

    【解决方案2】:

    在 ContentView 上设置环境如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2021-03-31
      • 2020-07-20
      • 2020-12-15
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多