我试图实现@EnvironmentObject,将数组从一个选项卡中的View传递到另一个选项卡中的另一个视图。
我收到黄色编译器警告:
从未使用不可变值“reportView”的
初始化;考虑将其替换为“_”或删除它
在SceneDelegate.swift中
这是我的SceneDelegate.swift:
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var questionsAsked = QuestionsAsked()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
ProductsStore.shared.initializeProducts()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: MotherView().environmentObject(ViewRouter()))
self.window = window
window.makeKeyAndVisible()
}
let reportView = ReportView().environmentObject(questionsAsked)
}
}
这是我的ObservabelObject:
import Foundation
class QuestionsAsked: ObservableObject {
@Published var sectionThings = [SectionThing]()
@Published var memoryPalaceThings = [MemoryPalaceThing]()
}
我用:
@EnvironmentObject var questionsAsked: QuestionsAsked
在我看来,这将生成要传递的数据。
我传递的数据如下:
questionsAsked.sectionThings = testSectionThings ?? []
在要传递数据的视图中,我有:
@EnvironmentObject var questionsAsked: QuestionsAsked
然后,我按以下方式访问:
totalThings += questionsAsked.sectionThings.count
totalThings += questionsAsked.memoryPalaceThings.count
发布于 2022-07-01 12:08:08
这里的问题是,这条线是无用的,因为它不会出现在现场。唯一显示的视图是MotherView
。为了将questionsAsked
向下传递到该视图,您只需像其他.environmentObject
一样追加它。因此,应改为:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
// this really need to be @StateObject´s
@StateObject var viewRouter = ViewRouter()
@StateObject var questionsAsked = QuestionsAsked()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
ProductsStore.shared.initializeProducts()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
//Inject them here into the MotherView
window.rootViewController = UIHostingController(rootView: MotherView().environmentObject(viewRouter).environmentObject(questionsAsked))
self.window = window
window.makeKeyAndVisible()
}
}
}
在MotherView
和降序视图中,您现在可以通过@EnvironmentObject
包装器访问它们。
https://stackoverflow.com/questions/72832941
复制