当我加载一个UIView时,我如何在iPhone SDK上设置UITextField的最大字符数?


当前回答

适用于Swift 3.1或更高版本

首先添加协议UITextFieldDelegate

如:-

class PinCodeViewController: UIViewController, UITextFieldDelegate { 
.....
.....
.....

}

之后创建你的UITextField并设置委托

完成经验:-

import UIKit

class PinCodeViewController: UIViewController, UITextFieldDelegate {

let pinCodetextField: UITextField = {
    let tf = UITextField()
    tf.placeholder = "please enter your pincode"
    tf.font = UIFont.systemFont(ofSize: 15)
    tf.borderStyle = UITextBorderStyle.roundedRect
    tf.autocorrectionType = UITextAutocorrectionType.no
    tf.keyboardType = UIKeyboardType.numberPad
    tf.clearButtonMode = UITextFieldViewMode.whileEditing;
    tf.contentVerticalAlignment = UIControlContentVerticalAlignment.center
 return tf
  }()


 override func viewDidLoad() {
   super.viewDidLoad()
   view.addSubview(pinCodetextField)
    //----- setup your textfield anchor or position where you want to show it----- 


    // after that 
pinCodetextField.delegate = self // setting the delegate

 }
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return !(textField.text?.characters.count == 6 && string != "")
     } // this is return the maximum characters in textfield 
    }

其他回答

谢谢你奥古斯特!(Post)

这是我最终得到的代码:

#define MAX_LENGTH 20

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length >= MAX_LENGTH && range.length == 0)
    {
        return NO; // return NO to not change text
    }
    else
    {return YES;}
}

我根据@Frouo给出了补充答案。我认为他的回答是最美丽的方式。因为这是一个我们可以重用的通用控件。

private var kAssociationKeyMaxLength: 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)
            self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
        }
    }

    func checkMaxLength(textField: UITextField) {

        guard !self.isInputMethod(), let prospectiveText = self.text,
            prospectiveText.count > maxLength
            else {
                return
        }

        let selection = selectedTextRange
        let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
        text = prospectiveText.substring(to: maxCharIndex)
        selectedTextRange = selection
    }

    //The method is used to cancel the check when use Chinese Pinyin input method.
    //Becuase the alphabet also appears in the textfield when inputting, we should cancel the check.
    func isInputMethod() -> Bool {
        if let positionRange = self.markedTextRange {
            if let _ = self.position(from: positionRange.start, offset: 0) {
                return true
            }
        }
        return false
    }

}

在Swift 5.2中工作:

 class AngListVC: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var angTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        angTextField.delegate = self
        angTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
      
    }

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
           let userText =  angTextField.text ?? ""
           var newText = ""
           if range.length > 0 {
               let txt = NSString(string: userText)
               if txt.length > 0 {
                   newText = txt.replacingCharacters(in: range, with: "")
               }
           } else {
               newText = userText + ""
           }
           return newText.count <= 3
       }

@objc func textFieldDidChange(_ textField: UITextField) {
        print("textFieldDidChange")
   }

如果您限制文本计数的目的是确保文本可以适合其他地方的UILabel,那么我会避免使用字符计数。它会因为一些表情符号而崩溃(试图截断一个两倍大小的表情符号可能会导致应用程序崩溃)。这也是一些语言(如日语和汉语)的问题,它们有两步输入过程,简单的计数是行不通的。

我构建了一个UITextField下拉子类(MPC_CharacterLimitedTextField在github)。你输入预期的输出标签宽度,它将处理所有语言、表情符号和粘贴问题。不管字符数是多少,它只会收获符合标签的完整字符数。项目中有一个演示,所以你可以测试它,看看它是否是你需要的。希望它能帮助到和我一样有输出长度问题的人。

把它压缩到一行代码:)

将文本视图的委托设置为“self”,然后在你的.h中添加<UITextViewDelegate>,在你的.m中添加以下代码....你可以调整数字“7”为任何你想要的最大字符数。

-(BOOL)textView:(UITextView *)a shouldChangeTextInRange:(NSRange)b replacementText:(NSString *)c {
    return ((a.text.length+c.length<=7)+(c.length<1)+(b.length>=c.length)>0);
}

这段代码负责输入新字符、删除字符、选择字符然后输入或删除、选择字符并剪切、粘贴,以及选择字符并粘贴。

完成了!


另外,用位操作编写这段代码的另一种很酷的方法是

-(BOOL)textView:(UITextView *)a shouldChangeTextInRange:(NSRange)b replacementText:(NSString *)c {
    return 0^((a.text.length+c.length<=7)+(c.length<1)+(b.length>=c.length));
}