首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为@EnvironmentObject设置SceneDelegate时编译器警告

为@EnvironmentObject设置SceneDelegate时编译器警告
EN

Stack Overflow用户
提问于 2022-07-01 17:45:09
回答 1查看 29关注 0票数 -2

我试图实现@EnvironmentObject,将数组从一个选项卡中的View传递到另一个选项卡中的另一个视图。

我收到黄色编译器警告:

从未使用不可变值“reportView”的

初始化;考虑将其替换为“_”或删除它

在SceneDelegate.swift中

这是我的SceneDelegate.swift:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
import Foundation

class QuestionsAsked: ObservableObject {
    @Published var sectionThings = [SectionThing]()
    @Published var memoryPalaceThings = [MemoryPalaceThing]()
}

我用:

代码语言:javascript
运行
复制
@EnvironmentObject var questionsAsked: QuestionsAsked

在我看来,这将生成要传递的数据。

我传递的数据如下:

代码语言:javascript
运行
复制
questionsAsked.sectionThings = testSectionThings ?? []

在要传递数据的视图中,我有:

代码语言:javascript
运行
复制
@EnvironmentObject var questionsAsked: QuestionsAsked

然后,我按以下方式访问:

代码语言:javascript
运行
复制
totalThings += questionsAsked.sectionThings.count
totalThings += questionsAsked.memoryPalaceThings.count
EN

回答 1

Stack Overflow用户

发布于 2022-07-01 20:08:08

这里的问题是,这条线是无用的,因为它不会出现在现场。唯一显示的视图是MotherView。为了将questionsAsked向下传递到该视图,您只需像其他.environmentObject一样追加它。因此,应改为:

代码语言:javascript
运行
复制
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包装器访问它们。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72832941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档