NEW: Learn SwiftUI with my free YouTube video series! >>

How to add a placeholder to a TextField

Paul Hudson    @twostraws   

Fully updated for Xcode 11 GM

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 uses a prompt (“Enter your password”) or showing some example data.

To set a placeholder, 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(RoundedBorderTextFieldStyle())
            .padding()
    }
}

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.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5