【发布时间】:2020-06-11 06:35:31
【问题描述】:
当我长按默认键盘退格按钮时,有时它会清除所有文本,有没有办法只清除一个一个字符
【问题讨论】:
标签: ios objective-c swift uitextfield
当我长按默认键盘退格按钮时,有时它会清除所有文本,有没有办法只清除一个一个字符
【问题讨论】:
标签: ios objective-c swift uitextfield
您可以使用 textField shouldChangeCharactersIn 委托方法来处理,如下所示:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.isEmpty {
if range.length != 1 {
if let val: String = textField.text {
if !val.isEmpty {
let newStr: NSString = val as NSString
if newStr.length > 0 {
let updatedString: String = newStr.substring(to: newStr.length - 1)
textField.text = updatedString
}
}
}
return false
}
}
return true
}
【讨论】:
像这样实现UITextFieldDelegate's textField(_:shouldChangeCharactersIn:replacementString:)方法,
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.isEmpty {
textField.text?.removeLast()
return false
}
return true
}
【讨论】: