1:设置文本输入框的代理UITextFieldDelegate
self.pwdTextField.delegate = self;
2:在代理方法中加入限制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return [self validateNumber:string];
}
- (BOOL)validateNumber:(NSString*)number {
BOOL res = YES;
NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
int i = 0;
while (i < number.length) {
NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
NSRange range = [string rangeOfCharacterFromSet:tmpSet];
if (range.length == 0) {
res = NO;
break;
}
i++;
}
return res;
}
3:如果有字数要求,也在该代理方法中实现。
//交易密码长度
#define kTradePWD_LENGTH_LIMIT 6
#pragma mark - 限定文本框输入的文字个数
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * aString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([self validateNumber:string]) {
//文字长度限制
if ([aString length] > kTradePWD_LENGTH_LIMIT) {
textField.text = [aString substringToIndex:kTradePWD_LENGTH_LIMIT];
return NO;
}
}else
{
[MBProgressHUD showError:@"输入六位数字组合的密码"];
return NO;
}
return YES;
}
- (BOOL)validateNumber:(NSString*)number {
BOOL res = YES;
NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
int i = 0;
while (i < number.length) {
NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
NSRange range = [string rangeOfCharacterFromSet:tmpSet];
if (range.length == 0) {
res = NO;
break;
}
i++;
}
return res;
}