SPatel
SPatel

Reputation: 4946

backspace press not calling uitextfield's method

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

enter image description here

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

Upvotes: 0

Views: 441

Answers (3)

SPatel
SPatel

Reputation: 4946

I get solution by overriding Following Method of UITextField.

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

Upvotes: 1

jignesh Vadadoriya
jignesh Vadadoriya

Reputation: 3310

Directly Identify backspace is not proper logic. As per your requirement your text field become Blank then you want to previous text field become first responder then you need to write your code like this way

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    var txtAfterUpdate:NSString = textField.text! as NSString
    txtAfterUpdate = txtAfterUpdate.replacingCharacters(in: range, with: string) as NSString
    let updatedString = txtAfterUpdate as String

    if updatedString.characters.count == 0 {
        var tag = textField.tag
        tag -= 1
        let nextResponder = textField.superview?.viewWithTag(tag) as UIResponder!
        nextResponder?.becomeFirstResponder()

        return true
    } else{

        // rest of your functionality
    }

    return true
}

I hope it will help you.

Upvotes: 1

Abdul Rehman
Abdul Rehman

Reputation: 2456

There is code to detect backspace

 const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
    int isBackSpace = strcmp(_char, "\b");

        if (isBackSpace == -8) {
            // Code there
           }

Upvotes: 1

Related Questions