如何在 iOS 14 (Xcode 12 Beta) 中从 UIKit 生命周期转换为 SwiftUI 生命周期 [英] How to convert from UIKit life cycle to SwiftUI life cycle in iOS 14 (Xcode 12 Beta)

查看:27
本文介绍了如何在 iOS 14 (Xcode 12 Beta) 中从 UIKit 生命周期转换为 SwiftUI 生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发 SwiftUI 应用程序,其中使用了 SceneDelegateAppDelegate.我想知道如何将生命周期从 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 代码去哪儿了.我仍然很困惑这种转换是如何进行的.我没有看到 Apple 在他们的会议或任何事情中谈论过这个.非常感谢您的帮助.

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)
        }
    }
}

这篇关于如何在 iOS 14 (Xcode 12 Beta) 中从 UIKit 生命周期转换为 SwiftUI 生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆