Skip to main content

How to add a placeholder to a TextField

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

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()
    }
}

Download this as an Xcode projectopen in new window

A text field with a thin grey outline containing the placeholder text “johnnyappleseed@apple.com”.
A text field with a thin grey outline containing the placeholder text “johnnyappleseed@apple.com”.

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

이찬희 (MarkiiimarK)
Never Stop Learning.