简体   繁体   English

swiftUI 中的全局变量?

[英]Global variable in swiftUI?

I want to keep some Boolean state which is going to use in all over the app.我想保留一些将在整个应用程序中使用的布尔状态。 is there any way to make such global variable in swiftUI?有没有办法在 swiftUI 中创建这样的全局变量?

Thank You for help谢谢你的帮助

Use the @EnvironmentObject property wrapper for data shared with many views.对与许多视图共享的数据使用@EnvironmentObject属性包装器。 This lets us share model data anywhere it's needed, while also ensuring that the views automatically stay updated when that data changes.这让我们可以在任何需要的地方共享模型数据,同时还确保视图在数据更改时自动保持更新。

EnvironmentObject环境对象

A property wrapper type for an observable object supplied by a parent or ancestor view.由父视图或祖先视图提供的可观察对象的属性包装器类型。 https://developer.apple.com/documentation/swiftui/environmentobject https://developer.apple.com/documentation/swiftui/environmentobject

// Our observable object class
class GameSettings: ObservableObject {
    @Published var score = 0
}

// A view that expects to find a GameSettings object
// in the environment, and shows its score.
struct ScoreView: View {
    @EnvironmentObject var settings: GameSettings

    var body: some View {
        Text("Score: \(settings.score)")
    }
}

// A view that creates the GameSettings object,
// and places it into the environment for the
// navigation view.
struct ContentView: View {
    @StateObject var settings = GameSettings()

    var body: some View {
        NavigationView {
            VStack {
                // A button that writes to the environment settings
                Button("Increase Score") {
                    settings.score += 1
                }

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

Ref: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views参考: https : //www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

More info更多信息

https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app

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

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