How to add a placeholder to a TextField
About 2 min
How to add a placeholder to a TextField êŽë š
SwiftUI by Example
Back to Home
How to add a placeholder to a TextField | SwiftUI by Example
How to add a placeholder to a TextField
Updated for Xcode 15
SwiftUI's TextField
supports placeholder text just like UITextField
did â gray text that is shown in the text field when it's empty, either giving users a prompt (âEnter your passwordâ) or showing some example data.
To set your placeholder text, pass it in as part of the initializer for your text field, like this:
struct ContentView: View {
@State private var emailAddress = ""
var body: some View {
TextField("johnnyappleseed@apple.com", text: $emailAddress)
.textFieldStyle(.roundedBorder)
.padding()
}
}
Important
If you're using Xcode 12 you need to use RoundedBorderTextFieldStyle()
rather than .roundedBorder
.
That will show âjohnnyappleseed@apple.comâ in the text field while it's empty, but as soon as the user types something in there it disappears.
Similar solutionsâŠ
How to mark content as a placeholder using redacted() | SwiftUI by Example
How to mark content as a placeholder using redacted()
How to add a TextField to an alert | SwiftUI by Example
How to add a TextField to an alert
How to add a border to a TextField | SwiftUI by Example
How to add a border to a TextField
How to make a TextField expand vertically as the user types | SwiftUI by Example
How to make a TextField expand vertically as the user types
How to dismiss the keyboard for a TextField | SwiftUI by Example
How to dismiss the keyboard for a TextField