So I am working on a view where I want to have editable text which is only made editable via a button press. So basically, when pressing the "edit" button, a text field should be made editable, and the focus should be sent to the text field.
Here's how I have attempted to implement this:
struct MyView: View {
@Binding var text: String
@FocusState var isEditing
var body: some View {
HStack {
TextField("Text", text: $text)
.disabled(!isEditing)
.focused($isEditing)
Spacer()
Button(isEditing ? "Done" : "Edit") {
isEditing.toggle()
}
}
}
}
So if I comment out the .disabled
line, the focus behavior works as intended. However when the disabled call is there, pressing the edit button does not enable or focus the text field.
My best guess is that maybe the field cannot be focused because it's initially disabled?
Is there any way to achieve this behavior? I've also tried using a separate @State var for disabled and this has the same result.