我有一个UITextField
,其限制为只能输入数字,就像以下方法一样。我还想将最大字符数限制为3位数字。我该如何修改我的方法以实现这个目标?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar aCharacter = [string characterAtIndex:i];
if ([aCharacterSet characterIsMember:aCharacter]) {
return YES;
}
}
NSUInteger newLength = self.textField.text.length + string.length - range.length;
return (newLength > 3) ? NO : YES;
}