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:
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:
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.