一个用于在 UITextField 中处理国际电话号码的自定义格式化器。
您可以从 CocoaPods 或手动安装 STPhoneFormatter。如果您选择最麻烦的方法,请包括以下 3 个文件
STPhoneFormatter.h
STPhoneFormatter.m
FormatsCountriesPhone.plist
提供了两种不同的电话号码格式:已格式化的格式 @property formattedPhoneNumber
和未格式化的格式 - (NSString *)internationalPhoneNumber
。
您可以通过 @property countryCode
和 @property countryName
访问国家的代码和名称。
此外,您可以通过设置带有方法 - (BOOL)setCountryCode:(NSString *)countryCode;
的国家来自定义电话号码的格式。国家的代码必须遵守 ISO 3166。
如果您想通过添加更多国家来做出贡献,请以拉取请求的形式提交您自己的 .plist。
在 Xcode 中构建并运行 STPhoneFormatterExample 项目以查看 STPhoneFormatter
的实际操作。
首先,需要设置您的 UITextField 的代理,并在代理方法 (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
中添加以下内容
BOOL phoneNumberHasChanged = [[STPhoneFormatter phoneFormatter] phoneNumberMustChangeInRange:range replacementString:string];
if (phoneNumberHasChanged) {
textField.text = [[STPhoneFormatter phoneFormatter] formattedPhoneNumber];
}
return NO;
重要提示:不要忘记返回值 NO
。
Sebastien Thiebaud
STPhoneFormatter 在 MIT 许可证下可用。