Detect backspace Event in UITextField

Swift 4.2 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if let char = string.cString(using: String.Encoding.utf8) { let isBackSpace = strcmp(char, “\\b”) if (isBackSpace == -92) { print(“Backspace was pressed”) } } return true } Older Swift version func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let … Read more

How shouldChangeCharactersInRange works in Swift?

Swift 4, Swift 5 This method doesn’t use NSString // MARK: – UITextFieldDelegate extension MyViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) myvalidator(text: updatedText) } return true } … Read more

Allow only alphanumeric characters for a UITextField

Use the UITextFieldDelegate method -textField:shouldChangeCharactersInRange:replacementString: with an NSCharacterSet containing the inverse of the characters you want to allow. For example: // in -init, -initWithNibName:bundle:, or similar NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain]; – (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters { return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound); } // in -dealloc [blockedCharacters release]; Note that you’ll need … Read more

UITextField text change event

From proper way to do uitextfield text change call back: I catch the characters sent to a UITextField control something like this: // Add a “textFieldDidChange” notification method to the text field control. In Objective-C: [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; In Swift: textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) Then in the textFieldDidChange method you can examine the … Read more