hallux
hallux

Reputation: 83

Show placeholder and icon when TextField isEmpty

I am trying to add an icon ( SFSymbol) called "exclamationmark.triangle" if the field is empty to identify that it's a required text field. Below is the method I used. It works, but not properly. When the user clicks on a text field and starts typing after the first character keyboard goes away, so the user has to retap to continue typing.

if name.isEmpty {
   HStack {
      TextField("First & Last Name", text: $name)
      Image(systemName: "exclamationmark.triangle")
   }
} else {
   TextField("First & Last Name", text: $name)
}

Upvotes: 2

Views: 530

Answers (1)

Harshil Patel
Harshil Patel

Reputation: 1472

struct ContentView : View {
    @State var name: String = ""
    var body: some View {
        HStack {
            TextField("First & Last Name", text: $name)
            name.isEmpty ? Image(systemName: "exclamationmark.triangle") : nil
        }
    }
}

Upvotes: 2

Related Questions