【发布时间】:2017-03-20 17:37:31
【问题描述】:
如何在 iOS 中为自定义键盘实现自定义退格/删除按钮,以快速响应 UITextField 委托?
【问题讨论】:
标签: swift uitextfield uikeyboard
如何在 iOS 中为自定义键盘实现自定义退格/删除按钮,以快速响应 UITextField 委托?
【问题讨论】:
标签: swift uitextfield uikeyboard
我为此苦苦挣扎了一段时间,所以我想我会回答这个问题。以下代码响应在作为 UITextfield 的第一响应者的 uikeyboard 上按下的自定义退格键:
// 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: "");
}
}
【讨论】:
您可能会发现全局方法“droplast()”很有帮助。(还有一个“dropfirst”)
var stringToBeBackspace = "abcde"
dropLast(stringToBeBackspace) //.swift
字符串实际上是字符的集合,所以你也可以在字符串中做滑动字符,你可能会发现“countElements”对你有很大帮助。
【讨论】:
我现在这个问题早就得到了回答,但我想分享我基于 UIKeyInput 的方法(在 iOS9 和 Xcode 7- Swift 2 上测试)。
@IBAction func backspacePressed(btn: UIButton) {
if btn.tag == 101 {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
}
【讨论】:
斯威夫特 3.0.1
此答案对退格/删除按钮作出反应,但具有限制可输入文本字段的最大字符数的额外功能。因此,如果 textField 包含的字符多于最大数量,因为以编程方式将字符串插入到 textField 中,则您无法添加字符,但可以删除它们,因为 'range.length' 仅使用删除键返回 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
}
}
【讨论】: