A Boolean value that indicates whether the view associated with this environment allows user interaction.
This example shows 1) each Environment is independent; 2)
import SwiftUI
import Speech
struct ContentView: View {
var body: some View {
VStack {
// btn1
FirstButtonView {
print("first button")
}
.environment(\.isEnabled, false) // if you set here, then environment is independent
// btn2
SecondButtonView {
print("second button")
}
// .disabled(false) // will be overwritten by the above setting
// .environment(\.isEnabled, true)
// btn3
ThirdButtonView(action: {
print("third button")
}, isDisabled: false)
}
// .environment(\.isEnabled, false) // this will affect all subviews
}
}
struct FirstButtonView: View {
let action: () -> Void
@Environment(\.isEnabled) private var isEnabled
var body: some View {
Button(action: action) {
Text("First Button")
}
.foregroundColor(isEnabled ? .green : .gray)
}
}
struct SecondButtonView: View {
let action: () -> Void
@Environment(\.isEnabled) private var isEnabled
var body: some View {
Button(action: action) {
Text("Second Button")
}
.foregroundColor(isEnabled ? .green : .gray)
}
}
struct ThirdButtonView: View {
let action: () -> Void
@State var isDisabled: Bool
var body: some View {
Button(action: action) {
Text("Third Button")
}
.disabled(isDisabled)
.foregroundColor(isDisabled ? .gray : .green)
}
}