SwiftUI .autocorrectionDisabled() behavior not updating with @State BOOL

49 Views Asked by At

Using 'true' or 'false' works as expected:

TextEditor(text: $input)
    .autocorrectionDisabled(true)

But when replacing with a State variable, only the initial value is used. When the state value changes to 'false', the behavior of autocorrect doesn't change.

@State var shouldDisable = true  

TextEditor(text: $input)  
    .autocorrectionDisabled(shouldDisable)  
    .onReceive(aTimer) { _ in  
        if otherConditionMet {  
            withAnimation {  
                shouldDisable = false  
            }  
        print(shouldDisable)  
        }  
    }

The timer is firing every second to evaluate if otherConditionMet. Here's the output of the simple print statement confirming shouldDisable updates when the other condition is met:

`shouldDisable: true`
`shouldDisable: true`
`shouldDisable: true`
`shouldDisable: true`
`shouldDisable: true
`shouldDisable: false`
`shouldDisable: false`
`shouldDisable: false`

I've validated by initialing shouldDisable to true and again initializing to false and updating shouldDisable = true in the if statement. In both conditions, only the initial value is used, despite how the variable changes.

I've tried removing the withAnimation, as well as the order of the .autocorrectionDisabled modifier in the stack; neither had any effect.

I'm testing on a physical device with iOS 15 as this is my oldest supported target.

Thanks for any input!


Update: I just validated this behavior with the following bare-bones code. The bool toggles to false, but the TextEditor does not re-enable autocorrection:

struct ContentView: View {
    @State var input = ""
    @State var autocorrectionDisabled = true

    var body: some View {

        VStack {
            TextEditor(text: $input)
                .autocorrectionDisabled(autocorrectionDisabled)
                .font(.headline)
         
            Button("Toggle Autocorrection") {
                autocorrectionDisabled.toggle()
                print("autocorrectionDisabled: \(autocorrectionDisabled)")
            }
            .padding()
        }
        .padding()
    }
}

I'd be interested to hear others' results and ideas about how to work around this.

1

There are 1 best solutions below

1
lorem ipsum On

You can "reset" the TextField if you set the Bool as the id

TextEditor(text: $input)
    .autocorrectionDisabled(autocorrectionDisabled)
    .font(.headline)
    .id(autocorrectionDisabled)

This makes the TextField lose focus, so you would have to compensate for that using FocusState or leave it as is and expect to user to trigger focus.