我正在尝试验证在 UITextfield 中输入的 10 位电话号码。实际上我需要 xxx-xxx-xxxx 格式的数字。所以我不希望用户删除 - 符号。
我尝试使用此处提到的各种方法:Detect backspace in UITextField,但它们似乎都不起作用。
我目前的做法是:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (range.location == 12) {
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Invalid Input" message:@"Phone number can contain only 10 digits." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[testTextField resignFirstResponder];
return NO;
}
if (range.length == 0 && [blockedCharacters characterIsMember:[string characterAtIndex:0]]) {
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Invalid Input" message:@"Please enter only numbers.\nTry again." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
if (range.length == 0 &&
(range.location == 3 || range.location == 7)) {
textField.text = [NSString stringWithFormat:@"%@-%@", textField.text, string];
return NO;
}
if (range.length == 1 &&
(range.location == 4 || range.location == 8)) {
range.location--;
range.length = 2;
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
return YES;
}
对此有什么想法吗?
非常感谢你。