如何在iOS中为自定义键盘实现自定义退格/删除按钮,以响应swift中的UITextField委托?
答案 0 :(得分:1)
我一直在努力奋斗,所以我想我会回答这个问题。以下代码响应在ui键盘上按下的自定义退格键,该键盘是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: "");
}
}
答案 1 :(得分:0)
你可能会发现全局方法“droplast()”是一个很好的帮助。(还有一个“dropfirst”)
var stringToBeBackspace = "abcde"
dropLast(stringToBeBackspace) //.swift
字符串实际上是一个字符集合,因此您也可以在字符串中执行幻灯片字符,您可以找到“countElements”以获得很大的帮助。
答案 2 :(得分:0)
我现在很久以前就回答了这个问题,但我想基于UIKeyInput(在iOS9和Xcode 7-Swift 2上测试)分享我的方法。
@IBAction func backspacePressed(btn: UIButton) {
if btn.tag == 101 {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
}
答案 3 :(得分:0)
Swift 3.0.1
此答案对退格/删除按钮作出反应,但具有限制可输入textField的最大字符数的额外功能。因此,如果textField包含的字符多于最大数字,因为字符串以编程方式插入到textField中,则无法添加字符,但可以删除它们,因为&#39; range.length&#39;仅使用删除键返回1。
感谢OOPer提供限制字符数的原始代码。 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
}
}