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

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.

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

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

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

I am using @available (iOS 14.0, *) in the beginning:

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

}

}

}

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.

解决方案

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)

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值