How to set TextField keyboard type in iOS SwiftUI

SwiftUI’s TextField lets you select the keyboard type best suited for what input you’re expecting from users. This makes the user experience much more seamless.

This post will examine various keyboard types and how they can be implemented into SwiftUI.

What Is Keyboard Type? Keyboard type refers to the layout and features of a virtual keyboard displayed on screen. Depending on what content you expect to view, different types such as numeric, email or URL keyboards could be displayed accordingly.

Example for TextField Setting Keyboard Type in SwiftUI

Here’s an example of various text fields using various keyboard types:


import Foundation
import SwiftUI

struct ContentView: View {

    @State private var text1 = ""
    @State private var text2 = ""
    @State private var text3 = ""

    var body: some View {

        VStack {

            TextField("Default Keyboard", text: $text1)

            TextField("Number Pad", text: $text2)

            TextField("Email Keyboard", text: $text3)
                .keyboardType(.emailAddress) .padding()
        } .padding()

struct TextFiltering_Previews: PreviewProvider {
    static var previews: some View {

TextField swiftui Explanation of the Code:

Default Keyboard

By default, the keyboard type is a standard keyboard that includes letters, numbers, and punctuation.

Number Pad Keyboard

By using .keyboardType(.numberPad), you can display a keyboard that only includes numbers. This is ideal for fields where only numeric input is required.

Email Address Keyboard

Using .keyboardType(.emailAddress), the keyboard displays keys specific to entering an email address, like “@” and “.” symbols.

Other Keyboard Types

SwiftUI provides several keyboard types to suit different needs:

  • .default: The standard keyboard.
  • .asciiCapable: A keyboard with ASCII characters.
  • .numbersAndPunctuation: A number and punctuation keyboard.
  • .URL: A keyboard optimized for URL entry.
  • .numberPad: A numeric pad.
  • .phonePad: A phone pad.
  • .namePhonePad: A name and phone number pad.
  • .decimalPad: A numeric pad with a decimal point.
  • .twitter: A keyboard optimized for Twitter text entry.

Selecting the appropriate keyboard type for a text field in SwiftUI is a subtle but impactful way to improve user experience. It ensures that the user is presented with the most relevant keys for their input, reducing mistakes, and speeding up data entry.


Read More :


You may also like...