Created
March 10, 2019 09:15
-
-
Save tapoton/c5301d4cae0b1085694e0d4bb70f1c42 to your computer and use it in GitHub Desktop.
textField(_:shouldDeleteBackwardsCharactersIn:)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol MyTextFieldDelegate: UITextFieldDelegate { | |
/// Asks the delegate if the character before the cursor or currently selected text should be deleted. | |
/// | |
/// - Parameters: | |
/// - textField: The text field containing the text. | |
/// - range: Range of the text that is going to be deleted. If cursor is at the beginning, range's `location` and `length` are 0. | |
/// - Returns: `true` if the specified text range should be deleted; otherwise, `false` to keep the old text. | |
func textField(_ textField: MyTextField, shouldDeleteBackwardsCharactersIn range: NSRange) -> Bool | |
} | |
class MyTextField: UITextField { | |
override func deleteBackward() { | |
guard let delegate = delegate as? MyTextFieldDelegate, let range = selectedTextRange else { | |
super.deleteBackward() | |
return | |
} | |
let startIndex = offset(from: beginningOfDocument, to: range.start) | |
let endIndex = offset(from: beginningOfDocument, to: range.end) | |
let deleteRange: NSRange | |
if startIndex == endIndex { | |
if startIndex > 0 { | |
deleteRange = NSRange(location: startIndex - 1, length: 1) | |
} else { | |
deleteRange = NSRange(location: 0, length: 0) | |
} | |
} else { | |
deleteRange = NSRange(startIndex..<endIndex) | |
} | |
if delegate.textField(self, shouldDeleteBackwardsCharactersIn: deleteRange) { | |
super.deleteBackward() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment