Home > AI > IOS > SwiftUI >

EnvironmentValues

API

Example 1: System EnvironmentKey

struct ContentView: View {
    var body: some View {
        Text("Hello, world!\nHello, world!\nHello, world!")
            .padding()
            .environment(\.lineLimit, 2)
    }
}

Example 2: Customized EnvironmentKey

//1 create a customized environment key 
private struct MyEnvironmentKey: EnvironmentKey {
    static let defaultValue: String = "Default value"
}

extension EnvironmentValues {
    var myValue: String {
        get { self[MyEnvironmentKey.self] }
        set { self[MyEnvironmentKey.self] = newValue }
    }
}


// 2 access and set the environment key
struct ContentView: View {
    @State private var isPopped: Bool = true
    
    var body: some View {
        VStack {
            Text("Hello, world!")
            DetailView()
                .environment(\.myValue, "Good") // set
        }
        
    }
}

struct DetailView: View {
    @Environment(\.myValue) var ok: String // access
    
    var body: some View {
        Text(ok)
    }
}


Leave a Reply