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


当前回答

下面的代码类似于sickp的答案,但是正确地处理复制-粘贴操作。如果尝试粘贴超过限制的文本,下面的代码将截断文本以符合限制,而不是完全拒绝粘贴操作。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    static const NSUInteger limit = 70; // we limit to 70 characters
    NSUInteger allowedLength = limit - [textField.text length] + range.length;
    if (string.length > allowedLength) {
        if (string.length > 1) {
            // get at least the part of the new string that fits
            NSString *limitedString = [string substringToIndex:allowedLength];
            NSMutableString *newString = [textField.text mutableCopy];
            [newString replaceCharactersInRange:range withString:limitedString];
            textField.text = newString;
        }
        return NO;
    } else {
        return YES;
    }
}

其他回答

适用于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;}
}

这个简单的方法怎么样?它对我来说很好。

extension UITextField {

    func  charactersLimit(to:Int) {

        if (self.text!.count > to) {
            self.deleteBackward()
        }
    }
}

然后:

someTextField.charactersLimit(to:16)

最好的方法是设置文本更改通知。在视图控制器方法的-awakeFromNib中,你需要:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitTextField:) name:@"UITextFieldTextDidChangeNotification" object:myTextField];

然后在同一个类中添加:

- (void)limitTextField:(NSNotification *)note {
    int limit = 20;
    if ([[myTextField stringValue] length] > limit) {
        [myTextField setStringValue:[[myTextField stringValue] substringToIndex:limit]];
    }
}

然后链接出口myTextField到你的UITextField,它将不让你添加任何字符后,你达到限制。一定要把这个添加到你的dealloc方法中:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:myTextField];

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

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