SwiftUI TextField: Auto Capitalization


SwiftUI provides an inbuilt modifier called textInputAutocapitalization to control text Autocapitalization within TextField. Modifier has four values to choose from:

Characters: defines an autocapitalization behavior that will capitalize every letter.

Never: defines an autocapitalization behavior that will not capitalize anything.

Sentences: defines an autocapitalization behavior that will capitalize first letter in every sentence

Words: defines an autocapitalization behavior that will capitalize the first letter of every word.

In our example, we will use words for course title, characters for course category and never for course type.
struct TextFieldExample: View {
    
    @State private var title: String = ""
    @State private var category: String = ""
    @State private var type: String = ""
    
    var body: some View {
        VStack {
            Text("DevTechie Courses")
                .font(.largeTitle)
            
            VStack(alignment: .leading) {
                Text("Enter new course title")
                    .font(.title3)
                
                TextField("Course title", text: $title)
                    .textFieldStyle(.roundedBorder)
                    .textInputAutocapitalization(.words)
                    
                
                TextField("Course category", text: $category)
                    .textFieldStyle(.roundedBorder)
                    .textInputAutocapitalization(.characters)
                    
                
                TextField("Course type", text: $type)
                    .textFieldStyle(.roundedBorder)
                    .textInputAutocapitalization(.never)
                    
                
            }.padding(.top, 20)
        }.padding()
    }
}