Disable autocorrect in a TextField in SwiftUI

In this tutorial, we will see how to disable autocorrect in a TextField in SwiftUI.

Autocorrect is a built-in feature that automatically suggests and corrects words as users type. We basically disable autocorrect to type exactly what we want like passwords,  technical words, etc without any interruption.

.disableAutocorrection(true)using this modifier we can disable autocorrect in a TextField.

Now, follow the steps below to disable autocorrect in a TextField.

Create a TextField

First of all, I will create a TextField with the Rounded Borderd style and see how it corrects the words.

Example

import SwiftUI

struct ContentView: View {
    @State private var textField: String = ""
    
    var body: some View {
        TextField("Text goes here", text: $textField)
            .font(.largeTitle)
            .padding()
            .textFieldStyle(RoundedBorderTextFieldStyle())
    }
}

In the above program, I have created a rounded bordered ( using the .textFieldStyle() modifier ) text field (using the TextField view) that will take input from the users.

Output:

Disable autocorrect in a TextField in SwiftUI

Disable Autocorrect

We can disable the autocorrect by using the disableAutocorrection() modifier on the TextField.

Syntex

.disableAutocorrection(true)

The argumart inside the disableAutocorrection() has been set to true to turn off the feature that automatically suggests or changes words as we type in a text field.

We can directly apply this modifier to the TextField like below.

Example

import SwiftUI

struct ContentView: View {
    @State private var textField: String = ""
    
    var body: some View {
        TextField("Text goes here", text: $textField)
            .font(.largeTitle)
            .padding()
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .disableAutocorrection(true) // To disable autocorrect
    }
}

Output:

Disable autocorrect in a TextField in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *