在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)); }