问题描述
如何覆盖此UITextField函数,使其对最大字符数有所限制?
How can I override this UITextField function so that it will have a limit on the maximum number of characters?
override func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool {
}
我在堆栈上做了一些研究,但是我所能找到的就是这个功能(见下文)。首先,我看不到如何覆盖,其次,它使用NSRange作为我拥有UITextRange的参数。如何实现呢?谢谢
I've done some research on stack, but all I can find is this function (see below). First off, I can't see how this can be an override, and second, it's using NSRange as a parameter where I have UITextRange. How can this be implemented? thanks
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
}
错误:无法将类型 UITextRange的值转换为预期的参数类型 NSRange(又名 _NSRange)
error: Cannot convert value of type 'UITextRange' to expected argument type 'NSRange' (aka '_NSRange')
推荐答案
您可以将UITextField子类化,并为UIControlEvents editedChanged添加目标。在选择器方法内部,您可以使用集合方法前缀来限制添加到textfield文本属性中的字符,如下所示:
You can subclass UITextField and add a target for UIControlEvents editingChanged. Inside the selector method you can use collection method prefix to limit the characters added to your textfield text property as follow:
import UIKit
class LimitedLengthField: UITextField {
var maxLength: Int = 10
override func willMove(toSuperview newSuperview: UIView?) {
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
editingChanged()
}
@objc func editingChanged() {
text = String(text!.prefix(maxLength))
}
}
您可以添加自定义文本字段以编程方式或使用界面生成器:
You can add your custom text field programatically or using the interface builder:
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)
}
}
这篇关于UITextField在Swift中设置最大字符长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!