UITextField 设置最大字符长度 Swift

UITextField setting maximum character length in Swift

如何覆盖此 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
    }

错误:无法将类型 'UITextRange' 的值转换为预期的参数类型 'NSRange'(又名“_NSRange”)

您可以子类化 UITextField 并为 UIControlEvents editingChanged 添加目标。在选择器方法中,您可以使用集合方法前缀来限制添加到文本字段文本 属性 中的字符,如下所示:

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))
    }
}

您可以通过编程方式或使用界面生成器添加自定义文本字段:

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)
    }
}