Max length UITextField

后端 未结 18 1848
一个人的身影
一个人的身影 2020-11-30 17:42

When I\'ve tried How to you set the maximum number of characters that can be entered into a UITextField using swift?, I saw that if I use all 10 characters, I can\'t erase t

18条回答
  •  心在旅途
    2020-11-30 18:27

    you can extend UITextField and add an @IBInspectable object for handle it:

    SWIFT 5

    import UIKit
    private var __maxLengths = [UITextField: Int]()
    extension UITextField {
        @IBInspectable var maxLength: Int {
            get {
                guard let l = __maxLengths[self] else {
                    return 150 // (global default-limit. or just, Int.max)
                }
                return l
            }
            set {
                __maxLengths[self] = newValue
                addTarget(self, action: #selector(fix), for: .editingChanged)
            }
        }
        @objc func fix(textField: UITextField) {
            if let t = textField.text {
                textField.text = String(t.prefix(maxLength))
            }
        }
    }
    

    and after that define it on attribute inspector

    See Swift 4 original Answer

提交回复
热议问题