Reputation: 12044
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
?
Upvotes: 7
Views: 3787
Reputation: 125
MVVM + Combine way:
class RecoveryPasswordViewModel: ObservableObject {
@Published var email: String = ""
@Published var isValidTextFieldStatus = true
var cancellables = Set<AnyCancellable>()
init() {
setTextFieldToValidWhenUserDelete()
}
func setTextFieldToValidWhenUserDelete() {
$email
.scan("", { [weak self] previousInput, currentInput in
if previousInput.count > currentInput.count {
self?.isValidTextFieldStatus = true
}
return currentInput
})
.sink { _ in }
.store(in: &cancellables)
}
}
Upvotes: 2
Reputation: 2308
Well you could use a hacky way for this.
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.
Upvotes: 4