Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Format Text Input in a Text Field in SwiftUI
Written by Team Kodeco

In SwiftUI, managing and formatting the input in a text field is often necessary for better user experience and data validation. SwiftUI provides several view modifiers that allow you to control the keyboard type, text content type and autocapitalization behavior, among other things.

Let’s create a registration form where the user is asked to enter their full name and email address. For the full name, you want each word to be capitalized, while for the email address, you want all characters to be in lowercase. Here’s how you can achieve this:

struct ContentView: View {
  @State private var name: String = ""
  @State private var email: String = ""

  var body: some View {
    VStack(spacing: 16) {
      TextField("Enter Full Name", text: $name)
        .autocapitalization(.words)
        .textContentType(.name)
        .padding()

      TextField("Enter Email Address", text: $email)
        .autocapitalization(.none)
        .keyboardType(.emailAddress)
        .textContentType(.emailAddress)
        .padding()
    }
    .padding()
  }
}

Your preview should look like this:

A text field with formatting in SwiftUI.
A text field with formatting in SwiftUI.

Run it in the simulator and you’ll see the keyboard changes depending on whether you enter a name or an email address. This approach is particularly powerful when combined with using an optional binding to validate TextField input, as explained in “Create a Text Field With an Optional in SwiftUI” elsewhere in this section.

In this example, you have two TextField views. The first one is for entering the full name. You use the autocapitalization(.words) modifier to automatically capitalize the first letter of each word. The textContentType(.name) modifier suggests to the system that this text field is for name input, which can help with features like autofill.

The second TextField is for the email address. You use the autocapitalization(.none) modifier to disable automatic capitalization, as email addresses are typically lowercase. The keyboardType(.emailAddress) modifier presents a keyboard optimized for entering email addresses, while the textContentType(.emailAddress) modifier suggests to the system that this text field is intended for email input.

By effectively using these view modifiers, you can control and format user input in a TextField in SwiftUI to suit your application’s needs.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.