How do you implement a custom backspace/delete button for a custom keyboard in iOS that responds to a UITextField delegate in swift?
-
check this: http://stackoverflow.com/questions/28024197/how-to-create-a-button-that-have-same-functionality-as-apple-original-keyboard-b/28107466#28107466 – Dharmesh Kheni Jan 29 '15 at 11:11
4 Answers
I was struggling with this for a while so thought i would answer the question. The following code responds to a custom backspace key being pressed on a uikeyboard that is a first responder to a UITextfield:
// the tag for the backspace button
if tag == "<"{
//the range of the selected text (handles multiple highlighted characters of a uitextfield)
let range = textField.selectedTextRange?;
// if the range is empty indicating the cursor position is
// singular (no multiple characters are highlighted) then delete the character
// in the position before the cursor
if range!.empty {
let start = textField.positionFromPosition(range!.start, offset: -1);
let end = axiomBuilderTV.positionFromPosition(range!.end, offset: 0);
axiomBuilderTV.replaceRange(axiomBuilderTV.textRangeFromPosition(start, toPosition: end), withText: "");
}
// multiple characters have been highlighted so remove them all
else {
textField.replaceRange(range!, withText: "");
}
}

- 575
- 7
- 23
You may find global method "droplast()" to be a great help.(also there is a "dropfirst")
var stringToBeBackspace = "abcde"
dropLast(stringToBeBackspace) //.swift
String is actually a collection of characters, so you can also do slide character in a string which you may find "countElements" to be a great help.
I now this question has been answered long ago, But I would like to shared my approach based on UIKeyInput (tested on iOS9 and Xcode 7- Swift 2).
@IBAction func backspacePressed(btn: UIButton) {
if btn.tag == 101 {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
}

- 963
- 9
- 19
Swift 3.0.1
This answer reacts to backspace/delete button but has the extra feature of limiting maximum number of characters that can be typed into a textField. So if the textField contained more characters than the maximum number because a string inserted programmatically into a textField you cannot add characters but you can delete them because 'range.length' returns 1 only with the delete key.
Thanks go to OOPer for the original code which limits number of characters. https://forums.developer.apple.com/thread/14627
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Updates everytime character ie typed or deleted until Max set in textFieldLimit
let textFieldLimit = 30
if (range.length == 1) { // Delete button = 1 all others = 0
return true
} else {
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= textFieldLimit
}
}

- 107
- 1
- 8