我已经搜遍了所有地方,我已经看到了很多解决方案,但大多数都是“hackish”并且容易出错。
我正在尝试使用libPhoneNumber iOS Class NBAsYouTypeFormatter格式化UITextField上的电话号码。
但是,我找不到合适的使用方法。
以下是我的尝试。 (来自此帖子Phone number format ios)
var asYouTypeFormatter = NBAsYouTypeFormatter(regionCode: "US");
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == phoneTextField {
if range.length == 0 {
textField.text = asYouTypeFormatter.inputDigit(textField.text + string);
}
else if range.length == 1 {
textField.text = asYouTypeFormatter.removeLastDigit();
}
return false;
}
return true;
}
此代码确实检测到range.length
和它没有考虑如果用户选择一个或多个字符然后输入。
如果用户这样做,将导致它不是类型。
有没有人找到更优雅的方法解决这个问题?
答案 0 :(得分:0)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == phoneTextField {
if range.length == 0 {
textField.text = asYouTypeFormatter.inputDigit(textField.text + string);
} else {
// take the resulting string after the replacement
var resultString = textField.text.replacingCharacters(in: range,
with: replacementString)
// prepare the string to be usable by the NBAsYouTypeFormatter
resultString = String(string.characters.filter { "01234567890+".characters.contains($0)
// set the result on the text field
textField.text = asYouTypeFormatter.inputString(resultString);
}
return false;
}
return true;
}
注意:我正在用目标C编写代码,没有测试Swift语法,但是此解决方案的逻辑对我有用;
这是我的Objective-C工作代码:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// This is to let the user clear the text field
if ([resultString isEqualToString:@""]) { return YES; };
NBAsYouTypeFormatter *formatter = [[NBAsYouTypeFormatter alloc] initWithRegionCode:[[NSLocale currentLocale] countryCode]];
NSCharacterSet *allowedPhoneCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"+0123456789"];
resultString = [[resultString componentsSeparatedByCharactersInSet:
[allowedPhoneCharacterSet invertedSet]]
componentsJoinedByString:@""];
dispatch_async(dispatch_get_main_queue(), ^{
textField.text = [formatter inputString:resultString];
});
return NO;
}