gpt4 book ai didi

ios - 如何将 NSString 格式化为美国的电话号码?

转载 作者:行者123 更新时间:2023-11-28 20:33:31 28 4
gpt4 key购买 nike

我有一个简单的应用程序可以帮助招聘人员在事件中收集信息。一个表单字段用于电话号码,我想要一种简单的方法来在用户键入时重新格式化电话号码。

电话号码应随着用户键入而变化,因此一串数字的示例输出应如下所示:

1
1 (20)
1 (206) 55
1 (206) 555-55
1 (206) 555-5555

或者,如果用户没有在区号前输入 1,则电话号码会像这样演变:

(20)
(206) 55
(206) 555-55
(206) 555-5555

如果电话号码太长,那么它应该只显示一串数字:

20655555555555555

最佳答案

这是我所做的:UITextFieldDelegate 通过获取 UITextField 的文本处理 textField:shouldChangeCharactersInRange :replacementString: 方法,并运行我写的一个小方法:

-(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 = @"";
}

}

希望对你有帮助!

关于ios - 如何将 NSString 格式化为美国的电话号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11404851/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com