最近发现使用- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
代理方法进行输入长度控制时,出现在第三方键盘输入表情符号时键盘删除键失效的bug 代码如下:
// 限制 textField 输入长度
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// 出现第三方键盘输入表情符号时会出现键盘删除键失效的bug
if textField == name_TF {
let maxLength = 100
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else { return false }
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
return updatedText.count <= maxLength
}
return true
}
不深究只看结果
通过扩展UITextField的lk_maxLength
属性,实现输入长度的限制
import UIKit
extension UITextField {
// 增加扩展属性
private struct LKTextFieldMaxLengthAssociatedKeys {
static var maxLength = 0
}
@objc var lk_maxLength:Int {
get {
return objc_getAssociatedObject(self, &LKTextFieldMaxLengthAssociatedKeys.maxLength) as? Int ?? 0
}
set(newValue) {
self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
objc_setAssociatedObject(self, &LKTextFieldMaxLengthAssociatedKeys.maxLength, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
@objc private func checkMaxLength() {
guard let maxLength = objc_getAssociatedObject(self, &LKTextFieldMaxLengthAssociatedKeys.maxLength) as? Int,
maxLength > 0,
let prospectiveText = self.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
let newText = String(prospectiveText[..<maxCharIndex])
self.text = newText
selectedTextRange = selection
}
}
使用
name_TF.lk_maxLength = 10 // 限制名称长度