小编典典

UITextField在Swift中设置最大字符长度

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


阅读 306

收藏
2020-07-07

共1个答案

小编典典

您可以子类化UITextField并为UIControlEvents
editedChanged添加一个目标。在选择器方法内部,您可以使用集合方法前缀来限制添加到textfield text属性中的字符,如下所示:

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