UITextField setting maximum character length in Swift

前端 未结 1 1706
無奈伤痛
無奈伤痛 2020-12-12 05:55

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: UITex         


        
1条回答
  •  囚心锁ツ
    2020-12-12 06:33

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

    0 讨论(0)
提交回复
热议问题