Satish Vekariya Satish Vekariya - 5 days ago 6
iOS Question

Uitextfield's textfieldShouldReturn() method nor call when backspace press

enter image description here
I have four textField for purpose of OTP, and also set delegate to my viewcontroller in ViewDidLoad() method

I have also implement delegate method:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string.characters.count > 1 {
return false
} else {
var tag = textField.tag
if string.characters.count == 0 {
tag -= 1
} else {
tag += 1
}
textField.text = string
// Try to find next responder
let nextResponder = textField.superview?.viewWithTag(tag) as UIResponder!
nextResponder?.becomeFirstResponder()
}
return false
}



func textFieldShouldReturn(textField: UITextField) -> Bool {
print("BACKSPACE PRESSED")
return true
}


But both of this method not call when field is empty, actually i want clear text. Any Idea how to detect "backspace" is pressed when textfield is empty

Answer

I get solution by overriding Following Method of UITextField.

class MYTextField: UITextField {
    override func deleteBackward() {
        super.deleteBackward()
        delegate?.textFieldShouldReturn!(self)
        print("_____________BACKSPACE_PRESSED_____________")
    }
} 
Comments