微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

objective-c – 如何仅在UITextField中输入数字并限制最大长度?

在UITextField中,我们仅输入数字,并限制最多3个数字,我使用以下代码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(Nsstring *)string  {


    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];

    Nsstring *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    while (newLength < CHaraCTER_LIMIT) {
        return [string isEqualToString:filtered];
    }

/* Limits the no of characters to be enter in text field */

    return (newLength > CHaraCTER_LIMIT ) ? NO : YES; 

}

当我按长按文本框(如下图),并在两个数字之间输入字符串,它也允许所有特殊字符和承租人.

解决方法

不是我不喜欢 the answer I wrote at this question,那也是 copy & pasted这里.我会尝试解释你的错误.

这个答案是基于你的常量定义如下的假设:

#define NUMBERS_ONLY @"1234567890"
#define CHaraCTER_LIMIT 3

您的逻辑失败的原因是,当newLength将等于CHaraCTER_LIMIT时,您永远不会处理该事件.

为了说明你的文本框是空的,你要求将字符串@“ABC”粘贴到文本域,你的委托方法调用.您创建过滤的字符串,正确计算为空字符串,您不能等待执行行return [string isEqualToString:filtered];但是,由于newLength为3,因此您不符合while循环的条目要求,所以您从未真正评估该行.所以简单的return(newLength> CHaraCTER_LIMIT)?不:是决定返回值.

如果您的CHaraCTER_LIMIT由于某种原因实际上为4,则只需将“ABCD”设为逻辑仍然适用的字符串即可.

这是一个简单的例子,您的功能更正了工作.再次,我假设CHaraCTER_LIMIT等于3.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(Nsstring *)string  {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
    Nsstring *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return (([string isEqualToString:filtered])&&(newLength <= CHaraCTER_LIMIT));
}

原文地址:https://www.jb51.cc/c/113352.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐