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

< How to add a border to a TextField   How to create secure text fields using SecureField >

How to add a placeholder to a TextField

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 var emailAddress = ""

    var body: some View {
        TextField("johnnyappleseed@apple.com", text: $emailAddress)
            .textFieldStyle(.roundedBorder)
            .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.

Tip: In beta 1 and 2 you should use TextField($emailAddress, placeholder: Text("johnnyappleseed@apple.com")) instead.

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!

< How to add a border to a TextField   How to create secure text fields using SecureField >
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 me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>