简体   繁体   English

如何在 swiftUI 中使用 EnvironmentObject 获取原始 object 的价值

[英]How to get value on original object with EnvironmentObject in swiftUI

class GameSettings: ObservableObject {
    @Published var score = 0
    @Published var score1:Int? = 0
}


struct ScoreView: View {
    @EnvironmentObject var settings: GameSettings
    var body: some View {
        NavigationView {
            NavigationLink(destination: ContentView3()) {
                Text("Score: \(settings.score)")
            }
        }
    }
}

struct ContentView3: View {
    @StateObject var settings = GameSettings()
    @EnvironmentObject var settings111: GameSettings

    var body: some View {
        NavigationView {
            VStack {
                // A button that writes to the environment settings
                Text("Current Score--->\(settings.score))")
                Text(settings111.score1 == nil ? "nil" : "\(settings111.score1!)")
                Button("Increase Score") {
                    settings.score += 1
                }

                NavigationLink(destination: ScoreView()) {
                    Text("Show Detail View")
                }
            }
            .frame(height: 200)
        }
        .environmentObject(settings)
    }
}

So here When user has performed some changes in ContentView3 & from navigation route if user lands to same screen ie ContentView3 so how can I get GameSettings object latest value on it?因此,当用户在ContentView3和导航路线中执行了一些更改时,如果用户登陆到同一屏幕,即ContentView3 ,那么我怎样才能获得GameSettings object 的最新值呢? I tried creating @EnvironmentObject var settings111: GameSettings but crashes.我尝试创建@EnvironmentObject var settings111: GameSettings但崩溃。

Did you add .environmentObject() to your YourApp.swift as well?您是否也将.environmentObject()添加到 YourApp.swift 中?
If not, you have to add it like this如果没有,您必须像这样添加它

Life Cycle: SwiftUI生命周期:SwiftUI

@main
struct YourApp: App {
    var settings: GameSettings = GameSettings()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(settings)
        }
    }
}

Life Cycle: UIKit生命周期:UIKit

In SceneDelegate.swift在 SceneDelegate.swift

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()
        var settings: GameSettings = GameSettings() // added line

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView.environmentObject(settings))) // added ".environmentObject(settings)" after contentView
            self.window = window
            window.makeKeyAndVisible()
        }
    }

Preview预习

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(GameSettings())
    }
}

在此处输入图像描述

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM