Set the maximum character length of a UITextField

前端 未结 30 1643
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  抹茶落季
    2020-11-22 02:44

    Use below extension to set the maximum character length of a UITextField and UITextView.

    Swift 4.0

        private var kAssociationKeyMaxLength: Int = 0
        private var kAssociationKeyMaxLengthTextView: Int = 0
        extension UITextField {
    
    
            @IBInspectable var maxLength: Int {
                get {
                    if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
                        return length
                    } else {
                        return Int.max
                    }
                }
                set {
                    objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
                    addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
                }
            }
    
            @objc func checkMaxLength(textField: UITextField) {
                guard let prospectiveText = self.text,
                    prospectiveText.count > maxLength
                    else {
                        return
                }
    
                let selection = selectedTextRange
    
                let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
                let substring = prospectiveText[..

    UITextView

    extension UITextView:UITextViewDelegate {
    
    
            @IBInspectable var maxLength: Int {
                get {
                    if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLengthTextView) as? Int {
                        return length
                    } else {
                        return Int.max
                    }
                }
                set {
                    self.delegate = self
    
                    objc_setAssociatedObject(self, &kAssociationKeyMaxLengthTextView, newValue, .OBJC_ASSOCIATION_RETAIN)
                }
            }
    
            public func textViewDidChange(_ textView: UITextView) {
                checkMaxLength(textField: self)
            }
            @objc func checkMaxLength(textField: UITextView) {
                guard let prospectiveText = self.text,
                    prospectiveText.count > maxLength
                    else {
                        return
                }
    
                let selection = selectedTextRange
    
                let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
                let substring = prospectiveText[..

    You can set limit below.

提交回复
热议问题