这是我所做的:通过获取文本来UITextFieldDelegate
处理方法,并运行我编写的一个小方法:textField:shouldChangeCharactersInRange :replacementString:
UITextField
-(void)updatePhoneNumberWithString:(NSString *)string {
NSMutableString *finalString = [NSMutableString new];
NSMutableString *workingPhoneString = [NSMutableString stringWithString:string];
if (workingPhoneString.length > 0) {
//This if statement prevents errors when the user deletes the last character in the textfield.
if ([[workingPhoneString substringToIndex:1] isEqualToString:@"1"]) {
//If the user typed a "1" as the first digit, then it's a prefix before the area code.
[finalString appendString:@"1 "];
[workingPhoneString replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];
}
if (workingPhoneString.length < 3) {
//If the user is dialing the area code...
[finalString appendFormat:[NSString stringWithFormat:@"(%@)", workingPhoneString]];
} else if (workingPhoneString.length < 6) {
//If the user is dialing the 3 digits after the area code...
[finalString appendFormat:[NSString stringWithFormat:@"(%@) %@",
[workingPhoneString substringWithRange:NSMakeRange(0, 3)],
[workingPhoneString substringFromIndex:3]]];
} else if (workingPhoneString.length < 11) {
//If the user is dialing the last 4 digits of the phone number...
[finalString appendFormat:[NSString stringWithFormat:@"(%@) %@-%@",
[workingPhoneString substringWithRange:NSMakeRange(0, 3)],
[workingPhoneString substringWithRange:NSMakeRange(3, 3)],
[workingPhoneString substringFromIndex:6]]];
} else {
//If the user's typed in a bunch of characters, then just show the full string.
finalString = phoneString;
}
phoneNumberField.text = finalString;
} else {
//If the user changed the textfield to contain no text at all...
phoneNumberField.text = @"";
}
}
希望这对你有帮助!