我只需要允许最终用户输入 1-9 位数字:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([newString length]>=1)
{
NSString *sepStr=[newString substringToIndex:1];
return !([sepStr length]>1);
}
if ([string length] == 0 && range.length > 0){
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
return NO;
}
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
if ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0)return YES;
return NO;
}
但仍然可以输入超过 1 个数字。请帮助查找错误。