Set the maximum character length of a UITextField

前端 未结 30 1658
难免孤独
难免孤独 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:42

    There is generic solution for setting max length in Swift. By IBInspectable you can add new Attribute in Xcode Attribute Inspector.

    import UIKit
    private var maxLengths = [UITextField: Int]()
    extension UITextField {
    
        @IBInspectable var maxLength: Int {
            get {
                guard let length = maxLengths[self]
                else {
                    return Int.max
                }
                return length
            }
            set {
                maxLengths[self] = newValue
                addTarget(
                    self,
                    action: Selector("limitLength:"),
                    forControlEvents: UIControlEvents.EditingChanged
                )
            }
        }
    
        func limitLength(textField: UITextField) {
            guard let prospectiveText = textField.text
                where prospectiveText.characters.count > maxLength else {
                    return
            }
            let selection = selectedTextRange
            text = prospectiveText.substringWithRange(
                Range(prospectiveText.startIndex ..< prospectiveText.startIndex.advancedBy(maxLength))
            )
            selectedTextRange = selection
        }
    
    }
    

提交回复
热议问题