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;
}
注意:我是用 Objective 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;
}