If I simply have a Button
where I have a state variable bind to its .disabled
modifier, then it works nice, as expected:
struct TestView: View {
@State private var saveEnabled: Bool = true
var body: some View {
Text("Tap me!")
.onTapGesture {
saveEnabled = !saveEnabled
}
Button("Save") {}
.disabled(!saveEnabled)
}
}
With this code snippet, when the user taps the text, the button is either enabled with blue tint or disabled with greyed out tint.
But when I try to do the same within a presented alert, it does not work. My use case is that I present a text field which is prepopulated with a non empty string and then I let the user to change that, but if that's empty, I don't want to let the user to save it, so I want to disable the Button
. This concept works fine in UIKit
with UIAlertController
and UITextField
- here I'm not sure why doesn't it work.
Code snippet:
struct TestView: View {
@State private var saveEnabled: Bool = true
var body: some View {
Text("Tap me!")
.onTapGesture {
presentAlert = true
}
.alert("Change name", isPresented: $presentAlert, actions: {
TextField("", text: $name)
.onChange(of: name) { newValue in
saveEnabled = !newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
Button("Save") {}
.disabled(!saveEnabled)
}
)
}
}
Should I file a ticket in Feedback Assistant or is there something I'm overlooking? Thanks.