Set the maximum character length of a UITextField

前端 未结 30 2317
难免孤独
难免孤独 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 03:04

    Swift 3 version //***** This will NOT work with Swift 2.x! *****//

    First create a new Swift file : TextFieldMaxLength.swift, and then add the code below:

    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),
             for: UIControlEvents.editingChanged
          )
       }
    }
    func limitLength(textField: UITextField) {
        guard let prospectiveText = textField.text,
            prospectiveText.characters.count > maxLength
        else {
            return
        }
    
       let selection = selectedTextRange
       let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
       text = prospectiveText.substring(to: maxCharIndex)
       selectedTextRange = selection
       }
    }
    

    and then you will see in Storyboard a new field (Max Length) when you select any TextField

    if you still have more questions check out this link: http://www.globalnerdy.com/2016/05/18/ios-programming-trick-how-to-use-xcode-to-set-a-text-fields-maximum-length-visual-studio-style/

提交回复
热议问题