Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Style a Text Field in SwiftUI
Written by Team Kodeco

Styling text fields in SwiftUI is a breeze thanks to its various view modifiers that you can use to control the font, color, padding, and more. Let’s learn how to style a text field in SwiftUI.

You can use SwiftUI’s view modifiers to customize the appearance of the text field. Here’s an example of a styled text field:

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

  var body: some View {
    TextField("Enter text", text: $inputText)
      .font(.title)
      .foregroundColor(.purple)
      .padding()
      .background(.yellow.opacity(0.2))
      .cornerRadius(10)
  }
}

Your preview will look like this:

A styled text field in SwiftUI.
A styled text field in SwiftUI.

In this example, you’re using the font modifier to set the font size to title, the foregroundColor modifier to change the text color to purple and the padding modifier to add some padding around the text field. Additionally, you use the background modifier to set a semitransparent yellow background color and the cornerRadius modifier to round the corners of the text field.

In SwiftUI, you can also change the text field’s border style using the textFieldStyle modifier. For instance, to set a rounded border:

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

  var body: some View {
    TextField("Enter text", text: $inputText)
      .textFieldStyle(.roundedBorder)
      .padding()
  }
}

Here’s what your preview will look like after entering some text:

A text field with a rounded border in SwiftUI.
A text field with a rounded border in SwiftUI.

In this example, the .roundedBorder applies a rounded border around the text field.

By using these view modifiers, you can style your text fields in SwiftUI to perfectly fit your app’s design.

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.