如何覆盖此UITextField函数以使其对最大字符数有限制?
override func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool {
}
我已经对堆栈进行过一些研究,但我能找到的就是这个函数(见下文)。首先,我无法看到这是一个覆盖,其次,它使用NSRange作为我有UITextRange的参数。如何实施?感谢
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let currentString: NSString = textField.text! as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= 4
}
我的失败尝试:
override func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool {
let currentString: NSString = self.text! as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: text) as NSString
return newString.length <= 4
}
错误:无法转换类型的值&#39; UITextRange&#39;预期的论证类型&#39; NSRange&#39; (又名&#39; _NSRange&#39;)
答案 0 :(得分:1)
您可以为UITextField创建子类,并为UIControlEvents editingChanged添加目标。在selector方法中,您可以使用collection方法前缀来限制添加到textfield文本属性中的字符,如下所示:
import UIKit
class LimitedLengthField: UITextField {
var maxLength: Int = 10
override func willMove(toSuperview newSuperview: UIView?) {
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
editingChanged(self)
}
@objc func editingChanged(_ textField: UITextField) {
guard let text = textField.text else { return }
textField.text = String(text.prefix(maxLength))
}
}
您可以以编程方式或使用界面构建器添加自定义文本字段:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let limitedLenghtField = LimitedLengthField(frame: CGRect(origin: CGPoint(x: 50, y: 50), size: CGSize(width: 200, height: 50)))
limitedLenghtField.text = "123456789012345"
view.addSubview(limitedLenghtField)
}
}