设置 UITextField 最大长度

发布于 2024-08-26 15:43:25 字数 71 浏览 8 评论 0原文

有没有办法设置 UITextField 的最大长度?

类似于 HTML 输入字段中的 MAXLENGTH 属性。

Is there any way to set the maximum length on a UITextField?

Something like the MAXLENGTH attribute in HTML input fields.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

时光是把杀猪刀 2024-09-02 15:43:25

这可以正确地与退格键和复制&一起使用。粘贴:

#define MAXLENGTH 10

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

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAXLENGTH || returnKey;
}

更新:更新为接受返回键,即使在最大长度时也是如此。谢谢罗杰斯先生!

This works correctly with backspace and copy & paste:

#define MAXLENGTH 10

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

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAXLENGTH || returnKey;
}

UPDATE: Updated to accept the return key even when at MAXLENGTH. Thanks Mr Rogers!

我不是你的备胎 2024-09-02 15:43:25

更新

我无法删除此答案,因为它已被接受,但它不正确。这是正确的代码,从下面的 TomA 复制:

#define MAXLENGTH 10

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

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAXLENGTH || returnKey;
}

ORIGINAL

我认为你的意思是 UITextField。如果是,那么有一个简单的方法。

  1. 实现 UITextFieldDelegate 协议
  2. 实现 < code>textField:shouldChangeCharactersInRange:replacementString: 方法。

每次角色点击或之前的角色替换时都会调用该方法。在这个方法中,你可以这样做:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH) {
        textField.text = [textField.text substringToIndex:MAXLENGTH-1];
        return NO;
    }
    return YES;
}

UPDATE

I cannot delete this answer because it is the accepted one, but it was not correct. Here is the correct code, copied from TomA below:

#define MAXLENGTH 10

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

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAXLENGTH || returnKey;
}

ORIGINAL

I think you mean UITextField. If yes, then there is a simple way.

  1. Implement the UITextFieldDelegate protocol
  2. Implement the textField:shouldChangeCharactersInRange:replacementString: method.

That method gets called on every character tap or previous character replacement. in this method, you can do something like this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH) {
        textField.text = [textField.text substringToIndex:MAXLENGTH-1];
        return NO;
    }
    return YES;
}
岛徒 2024-09-02 15:43:25

正确处理退格并将字符限制为提供的长度限制的更好函数如下:

#define MAXLENGTH 8

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        int length = [textField.text length] ;
        if (length >= MAXLENGTH && ![string isEqualToString:@""]) {
            textField.text = [textField.text substringToIndex:MAXLENGTH];
            return NO;
        }
        return YES;
    }

干杯!

A better function which handles backspaces correctly and limits the characters to the supplied length limit is the following:

#define MAXLENGTH 8

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        int length = [textField.text length] ;
        if (length >= MAXLENGTH && ![string isEqualToString:@""]) {
            textField.text = [textField.text substringToIndex:MAXLENGTH];
            return NO;
        }
        return YES;
    }

Cheers!

若水般的淡然安静女子 2024-09-02 15:43:25

此代码限制文本,同时还允许您输入字符或粘贴到文本中的任意位置。如果生成的文本太长,它会更改范围中的字符并将生成的文本截断到限制。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength = [textField.text length] - range.length + [string length];
    if (newLength >= MAXLENGTH) {
        textField.text = [[textField.text stringByReplacingCharactersInRange:range withString:string] substringToIndex:MAXLENGTH];
        return NO;
    }
    return YES;
}

This code limits the text while also allowing you enter characters or paste anywhere into the text. If the resulting text would be too long it changes the characters in the range and truncates the resulting text to the limit.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength = [textField.text length] - range.length + [string length];
    if (newLength >= MAXLENGTH) {
        textField.text = [[textField.text stringByReplacingCharactersInRange:range withString:string] substringToIndex:MAXLENGTH];
        return NO;
    }
    return YES;
}
春夜浅 2024-09-02 15:43:25

我认为这段代码可以解决这个问题:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range 
                                                       replacementString:(NSString*)string
{
   if (range.location >= MAX_LENGTH)
      return NO;
    return YES;
}

使用这个委托方法,您可以防止用户向文本字段添加超过 MAX_LENGTH 的字符,并且应该允许用户在需要时输入退格键。

I think this code would do the trick:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range 
                                                       replacementString:(NSString*)string
{
   if (range.location >= MAX_LENGTH)
      return NO;
    return YES;
}

With this delegate method you can prevent the user to add more characters than MAX_LENGTH to your text field and the user should be allowed to enter backspaces if needed.

孤独难免 2024-09-02 15:43:25

对我来说这有魔力:

if (textField.text.length >= 10 && range.length == 0)
    return NO;
return YES;

For me this did the magic:

if (textField.text.length >= 10 && range.length == 0)
    return NO;
return YES;
稀香 2024-09-02 15:43:25

这就是我解决这个问题的方法。当达到最大限制时,它不会尝试添加更多...您只能删除字符

#define MAX_SIZE ((int) 5)
...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] >= MAX_SIZE && ![string isEqualToString:@""]) {
        return NO;
    }

    return YES;
}

this is how i resolved that problem. When max limit is reached it wont try to add more... you will only be able to remove chars

#define MAX_SIZE ((int) 5)
...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] >= MAX_SIZE && ![string isEqualToString:@""]) {
        return NO;
    }

    return YES;
}
韬韬不绝 2024-09-02 15:43:25

我认为没有这样的财产。

但是分配给 UILabel 的文本必须是 NSString。在将此字符串分配给 UILabel 的文本属性之前,您可以使用 NSString 的以下方法在给定索引(您的最大长度)处裁剪字符串:

- (NSString *)substringToIndex:(NSUInteger)anIndex

I think there's no such property.

But the text you assign to the UILabel has to be an NSString. And before you assign this string to the UILabel's text property you can for example use the following method of NSString to crop the string at a given index (your maxlength):

- (NSString *)substringToIndex:(NSUInteger)anIndex
春风十里 2024-09-02 15:43:25

这与 coneybeare 的答案类似,但现在文本字段最多可以包含 MAXLENGTH 符号:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH - 1) {
        textField.text = [textField.text substringToIndex:MAXLENGTH];
        return NO;
    }
    return YES;
}

This is similar to coneybeare's answer, but now the text field can contain a maximum of MAXLENGTH symbols:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH - 1) {
        textField.text = [textField.text substringToIndex:MAXLENGTH];
        return NO;
    }
    return YES;
}
︶葆Ⅱㄣ 2024-09-02 15:43:25

您必须了解文本放置的位置以及添加的文本的长度(以防粘贴多个字符)。它们之间关于最大长度的模式是它们的总和永远不应超过最大长度。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger locationAndStringLengthSum = range.location + [string length];

    if ([textField isEqual:_expirationMonthField]) {
        if (locationAndStringLengthSum > EXP_MONTH_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_expirationYearField]) {
        if (locationAndStringLengthSum > EXP_YEAR_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_securityCodeField]) {
        if (locationAndStringLengthSum > SECURITY_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_zipCodeField]) {
        if (locationAndStringLengthSum > ZIP_CODE_MAX_CHAR_LENGTH) {
            return NO;
        }
    }

    return YES;
}

You have to be aware of the location the text is placed in as well as the length of text being added (in case they're pasting more than one character). The pattern between these with respect to max length is that their sum should never exceed the max length.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger locationAndStringLengthSum = range.location + [string length];

    if ([textField isEqual:_expirationMonthField]) {
        if (locationAndStringLengthSum > EXP_MONTH_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_expirationYearField]) {
        if (locationAndStringLengthSum > EXP_YEAR_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_securityCodeField]) {
        if (locationAndStringLengthSum > SECURITY_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_zipCodeField]) {
        if (locationAndStringLengthSum > ZIP_CODE_MAX_CHAR_LENGTH) {
            return NO;
        }
    }

    return YES;
}
嘿嘿嘿 2024-09-02 15:43:25

您需要在 ViewDidLoad 上分配委托

TextFieldname.delegate=self

You need to assign delegate on ViewDidLoad

TextFieldname.delegate=self
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文