Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

SwiftUI detect delete button pressed

I'm using SwiftUI, but I'm coding my own custom text mask, but I need to delete when a user press the "delete" key. I'm using the onChange method, but it is not detecting when special keys are pressed. Currently I'm using:

TextField(self.placeholder, text: self.$text)
.onChange(of: self.text, perform: { value in
    print(value)
})

Is there a way to detect if the delete button is pressed? Or should I use the UITextField instead of TextField ?

question from:https://stackoverflow.com/questions/66056424/swiftui-detect-delete-button-pressed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well you could use a hacky way for this.

  • First we will hold a count of the current characters the text string has.
  • Whenever the user presses backspace we check in the onChange handler if the previous character count is higher than the new character count
  • if that is the case we delete the whole string, or whatever you want to do when the delete button is pressed.
import SwiftUI
struct SquareView: View {
    
    var placeholder = "test"
    @State var text = "test"
    @State var textLen = 4
    
    var body: some View {
        VStack {
            TextField(self.placeholder, text: self.$text)
            .onChange(of: self.text, perform: { value in
                if value.count < textLen {
                    self.text = "" // << removed the whole text but here you can insert anything you want to do when the delete button is pressed
                }
                textLen = value.count
            })
        }
    }
}

Keep in mind that this is a hacky way and brings risks. For example if users paste something which is shorter than the current text.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...