【发布时间】:2010-01-27 12:53:28
【问题描述】:
在我的 iPhone 应用程序中,我有一个 textfield 来接受电话号码。我需要显示号码
美国电话号码格式。这就像(000)000-0000。通常像 iPhone 联系电话
号码输入。我怎样才能做到这一点。任何想法将不胜感激。
【问题讨论】:
标签: ios objective-c iphone phone-number
在我的 iPhone 应用程序中,我有一个 textfield 来接受电话号码。我需要显示号码
美国电话号码格式。这就像(000)000-0000。通常像 iPhone 联系电话
号码输入。我怎样才能做到这一点。任何想法将不胜感激。
【问题讨论】:
标签: ios objective-c iphone phone-number
对于自动格式化,我将addTarget 与PhoneNumberFormatter 结合使用,Adam 善意引用。实现描述为here。
【讨论】:
您将从
获得电话号码格式化程序http://the-lost-beauty.blogspot.com/2010/01/locale-sensitive-phone-number.html
不要忘记使用 PhoneNumberFormatter 类。该类在该博客中也可用
【讨论】:
由于用户在文本字段中手动输入电话号码,您可以使用 UITextFieldDelegate 方法textField:shouldChangeCharactersInRange:replacementString: 来动态更改输入的电话号码,方法是在输入 3 位数字后添加 '(' 在第 1 位之前 ')' '-' 后 6 位数字。
(或)数字输入完成后,您可以像这样更改显示格式:
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
//resign the keypad and check if 10 numeric digits entered...
NSRange range;
range.length = 3;
range.location = 3;
textField.text = [NSString stringWithFormat:@"(%@)%@-%@", [textField.text substringToIndex:3], [textField.text substringWithRange:range], [textField.text substringFromIndex:6];
}
【讨论】:
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
//resign the keypad and check if 10 numeric digits entered...
NSRange range;
range.length = 3;
range.location = 3;
textField.text = [NSString stringWithFormat:@"(%@) %@-%@", [textField.text substringToIndex:3], [textField.text substringWithRange:range], [textField.text substringFromIndex:6];
}
【讨论】: