3

我到处搜索,看到了很多解决方案,但其中大部分确实是“hackish”并且容易出错。

我正在尝试使用 libPhoneNumber iOS 类 NBAsYouTypeFormatter 格式化 UITextField 上的电话号码。

但是,我找不到正确的使用方法。

下面是我的尝试。(来自这个线程电话号码格式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它没有考虑用户是否选择一个或多个字符然后键入

如果用户这样做,将导致它不是类型。

有没有人找到一个更优雅的方法来解决这个问题?

4

1 回答 1

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;
}

注意:我是用 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;
}
于 2018-10-29T19:11:18.947 回答