Skip to content
DeveloperMemos

The keyboardType Modifier in SwiftUI

SwiftUI, Text Field, Keyboard Type1 min read

When building forms or input screens in SwiftUI, you may want to customize the keyboard type for text fields to make it easier for users to enter data. The keyboardType modifier in SwiftUI allows you to do just that.

Using the keyboardType Modifier

The keyboardType modifier is available on the TextField view in SwiftUI. It takes a UIKeyboardType value that specifies the type of keyboard to use for the text field.

Here's an example of how to use the keyboardType modifier to set the keyboard type to .numberPad:

1struct NumberInputView: View {
2 @State private var number: Int = 0
3
4 var body: some View {
5 TextField("Enter a number", value: $number, formatter: NumberFormatter())
6 .keyboardType(.numberPad)
7 }
8}

In this example, we've created a NumberInputView that contains a TextField with a placeholder text of "Enter a number". We've also bound the TextField to a @State variable called number using the $ prefix.

To set the keyboard type to .numberPad, we've added the keyboardType(.numberPad) modifier to the TextField.

You can use other UIKeyboardType values to customize the keyboard type for text fields. Here are some examples:

1TextField("Enter a phone number", text: $phoneNumber)
2 .keyboardType(.phonePad)
3
4TextField("Enter an email address", text: $emailAddress)
5 .keyboardType(.emailAddress)
6
7TextField("Enter a URL", text: $url)
8 .keyboardType(.URL)

Summary

The keyboardType modifier in SwiftUI allows you to customize the keyboard type for text fields, making it easier for users to enter data. By using the appropriate UIKeyboardType value, you can ensure that the keyboard provides the right set of keys for the type of data you're expecting.