SwiftUI provides various built-in text field styles that allow you to customize the appearance of text input fields. Understanding these styles helps you create consistent and polished user interfaces that match your app's design language.

What are TextField Styles?

TextField styles in SwiftUI are modifiers that change the visual appearance of text fields. SwiftUI includes several built-in styles like .automatic, .plain, and .roundedBorder, and you can also create custom styles using the TextFieldStyle protocol.

Built-in TextField Styles

Here are the main built-in text field styles:

import SwiftUI

struct TextFieldStylesView: View {
    @State private var text1 = ""
    @State private var text2 = ""
    @State private var text3 = ""

    var body: some View {
        Form {
            Section("Automatic Style") {
                TextField("Enter text", text: $text1)
                    .textFieldStyle(.automatic)
            }

            Section("Plain Style") {
                TextField("Enter text", text: $text2)
                    .textFieldStyle(.plain)
            }

            Section("Rounded Border Style") {
                TextField("Enter text", text: $text3)
                    .textFieldStyle(.roundedBorder)
            }
        }
    }
}

Creating Custom TextField Styles

You can create your own custom text field styles by conforming to the TextFieldStyle protocol:

struct CustomTextFieldStyle: TextFieldStyle {
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 10)
                    .fill(Color.blue.opacity(0.1))
            )
            .overlay(
                RoundedRectangle(cornerRadius: 10)
                    .stroke(Color.blue, lineWidth: 2)
            )
    }
}

struct ContentView: View {
    @State private var text = ""

    var body: some View {
        TextField("Custom styled field", text: $text)
            .textFieldStyle(CustomTextFieldStyle())
            .padding()
    }
}

Platform-Specific Considerations

Different platforms handle text field styles differently:

  • On iOS, .automatic typically provides an underlined style in forms

  • On macOS, the default style is plain with a focus ring

  • The .roundedBorder style provides the familiar rounded rectangle border

Accessibility

When customizing text field styles, ensure that:

  • Focus indicators remain visible for keyboard navigation

  • Color contrast meets accessibility guidelines

  • Touch targets are appropriately sized (at least 44x44 points)

Wrap up

TextField styles in SwiftUI cover most needs out of the box. If you need something more custom, TextFieldStyle is straightforward to implement.

Resources:

Read more

Share


Share Bluesky Mastodon Twitter LinkedIn Facebook