当我加载一个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;
    }
}

其他回答

你不能直接这样做- UITextField没有maxLength属性,但你可以设置UITextField的委托,然后使用:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

最好的方法是设置文本更改通知。在视图控制器方法的-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)。你输入预期的输出标签宽度,它将处理所有语言、表情符号和粘贴问题。不管字符数是多少,它只会收获符合标签的完整字符数。项目中有一个演示,所以你可以测试它,看看它是否是你需要的。希望它能帮助到和我一样有输出长度问题的人。

我发现这个方法又快又简单

- (IBAction)backgroundClick:(id)sender {
    if (mytext.length <= 7) {
        [mytext resignFirstResponder];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Too Big" 
                                                        message:@"Please Shorten Name"
                                                       delegate:nil 
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

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

extension UITextField {

    func  charactersLimit(to:Int) {

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

然后:

someTextField.charactersLimit(to:16)