1

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!

gavinmccabe
  • 165
  • 9

2 Answers2

4

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
  }
  • This is a very clever solution. I had to work quite hard at it to cover many scenarios in my use case but ultimately I achieved exactly what I wanted using this. And doesn't feel too much like a hack. Of course would be nice if they just add the detect delete functionality. – alionthego Jun 16 '23 at 00:25
0

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.

Intronaen
  • 158
  • 8