gavinmccabe
gavinmccabe

Reputation: 185

Detect Backspace in SwiftUI TextField

I've seen other questions on how to detect a backspace in an empty UITextField (UIKit). However, is there an easy way to do this with SwiftUI or using Introspect? Doing it with a textfield which is populated is quite simple, but I haven't been able to find a way to do it with an empty textfield.

Thank you!

Upvotes: 2

Views: 3629

Answers (2)

Toshiyuki Yasuno
Toshiyuki Yasuno

Reputation: 126

It has been a long time coming, but I have come up with an idea. (Not that I have thoroughly tested it). It is Hack-like.

The idea is to add Zero-Width Space (ZWSP) to the first character. By always adding ZWSP, even if the character appears to be zero, onChange/onReceive will occur because the ZWSP is actually present.

TextField("placeholder", text: $inputText)
  .onReceive(Just(inputText)) { text in
    if !text.hasPrefix("\u{200B}") {
      inputText = "\u{200B}" + text
    }
    // other code
  }

Upvotes: 11

Intronaen
Intronaen

Reputation: 176

I can't comment so I'll just put this as an answer instead. Even though it's for UIKit you can still wrap it in a UIViewRepresentable to place it in your SwiftUI code. You may know that already, so if you truly want pure SwiftUI, you may be out of luck here. Hopefully more TextField features are migrated to SwiftUI soon.

Upvotes: 0

Related Questions