【问题标题】:Phone number formatting on iOSiOS 上的电话号码格式
【发布时间】:2011-08-28 12:28:54
【问题描述】:

我有一个用户输入数据的文本字段。这是一个电话号码字段。如果用户输入1234567890,我希望它在用户输入时显示为(123)-(456)-7890。这怎么可能?

【问题讨论】:

    标签: objective-c ios cocoa-touch phone-number number-formatting


    【解决方案1】:

    这对你有帮助

    格式(xxx)xxx-xxxx

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        int length = (int)[self getLength:textField.text];
        //NSLog(@"Length  =  %d ",length);
    
        if(length == 10)
        {
            if(range.length == 0)
                return NO;
        }
    
        if(length == 3)
        {
            NSString *num = [self formatNumber:textField.text];
            textField.text = [NSString stringWithFormat:@"(%@) ",num];
    
            if(range.length > 0)
                textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];
        }
        else if(length == 6)
        {
            NSString *num = [self formatNumber:textField.text];
            //NSLog(@"%@",[num  substringToIndex:3]);
            //NSLog(@"%@",[num substringFromIndex:3]);
            textField.text = [NSString stringWithFormat:@"(%@) %@-",[num  substringToIndex:3],[num substringFromIndex:3]];
    
            if(range.length > 0)
                textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
        }
    
        return YES;
    }
    
    - (NSString *)formatNumber:(NSString *)mobileNumber
    {
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
    
        NSLog(@"%@", mobileNumber);
    
        int length = (int)[mobileNumber length];
        if(length > 10)
        {
            mobileNumber = [mobileNumber substringFromIndex: length-10];
            NSLog(@"%@", mobileNumber);
    
        }
    
        return mobileNumber;
    }
    
    - (int)getLength:(NSString *)mobileNumber
    {
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
    
        int length = (int)[mobileNumber length];
    
        return length;
    }
    

    【讨论】:

    • 非常感谢。它按我的意愿完美运行。这将对像我这样的初学者有很大帮助。
    • 我使用了你的代码。但是我将如何提及它是哪个文本字段。我在自定义 UITableviewcell 中有文本字段。请看我的编辑。
    • 为要格式化电话号码的文本字段设置标签,并根据标签值忽略其他文本字段
    • 选择删除一段电话号码就不行了
    • 这可能适用于快速而肮脏的解决方案,但缺乏很多我希望拥有的支持。对国际号码不起作用,对超过 10 位的号码不起作用,在删除字符或编辑字符时不格式化数字。
    【解决方案2】:

    这感觉更清晰,并且可以更好地处理删除任何不需要的字符。 1 (###) ###‑####(###) ###‑####

    的格式正确
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSArray *components = [newString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
        NSString *decimalString = [components componentsJoinedByString:@""];
    
        NSUInteger length = decimalString.length;
        BOOL hasLeadingOne = length > 0 && [decimalString characterAtIndex:0] == '1';
    
        if (length == 0 || (length > 10 && !hasLeadingOne) || (length > 11)) {
            textField.text = decimalString;
            return NO;
        }
    
        NSUInteger index = 0;
        NSMutableString *formattedString = [NSMutableString string];
    
        if (hasLeadingOne) {
            [formattedString appendString:@"1 "];
            index += 1;
        }
    
        if (length - index > 3) {
            NSString *areaCode = [decimalString substringWithRange:NSMakeRange(index, 3)];
            [formattedString appendFormat:@"(%@) ",areaCode];
            index += 3;
        }
    
        if (length - index > 3) {
            NSString *prefix = [decimalString substringWithRange:NSMakeRange(index, 3)];
            [formattedString appendFormat:@"%@-",prefix];
            index += 3;
        }
    
        NSString *remainder = [decimalString substringFromIndex:index];
        [formattedString appendString:remainder];
    
        textField.text = formattedString;
    
        return NO;
    }
    

    【讨论】:

    • 谢谢!相关问题的最佳解决方案,应该得到更多的支持。
    • 谢谢。我确实使用了 xxx-xxx-xxxx 格式的修改版本。
    • 我建议还向所有电话号码文本字段添加标签,并在删除其余号码时删除前导 1 -(void)textFieldDidEndEditing:(UITextField *)textField{ if (textField.tag == 99){ if([textField.text isEqualToString:@"1 "]){ textField.text = nil; } }
    • 或者修复这样的问题: BOOL hasLeadingOne = length > 0 && [decimalString characterAtIndex:0] == '1'; if(textField.text.length == 2 && 长度) 返回 YES; if (length == 0 || (length > 10 && !hasLeadingOne) || (length > 11)) { textField.text = decimalString;返回否; }
    • 还有一条正在使用的评论——如果你的文本字段很少——别忘了用textField.tag检查你正在验证的内容
    【解决方案3】:

    下面的代码是我通常使用的。格式不同,但你得到了图片。这将处理诸如'123df#$@$gdfg45-+678dfg901'之类的输入并输出'1 (234) 567-8901'

    #import "NSString+phoneNumber.h"
    
    @implementation NSString (phoneNumber)
    
    -(NSString*) phoneNumber{
        static NSCharacterSet* set = nil;
        if (set == nil){
            set = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        }
        NSString* phoneString = [[self componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
        switch (phoneString.length) {
            case 7: return [NSString stringWithFormat:@"%@-%@", [phoneString substringToIndex:3], [phoneString substringFromIndex:3]];
            case 10: return [NSString stringWithFormat:@"(%@) %@-%@", [phoneString substringToIndex:3], [phoneString substringWithRange:NSMakeRange(3, 3)],[phoneString substringFromIndex:6]];
            case 11: return [NSString stringWithFormat:@"%@ (%@) %@-%@", [phoneString substringToIndex:1], [phoneString substringWithRange:NSMakeRange(1, 3)], [phoneString substringWithRange:NSMakeRange(4, 3)], [phoneString substringFromIndex:7]];
            case 12: return [NSString stringWithFormat:@"+%@ (%@) %@-%@", [phoneString substringToIndex:2], [phoneString substringWithRange:NSMakeRange(2, 3)], [phoneString substringWithRange:NSMakeRange(5, 3)], [phoneString substringFromIndex:8]];
            default: return nil;
        }
    }
    
    @end
    

    【讨论】:

    • 如果长度小于7,最好默认返回PhoneNumberString。
    【解决方案4】:

    我们在这里为电话号码编写了一个自定义的 NSFormatter 子类:https://github.com/edgecase/PhoneNumberFormatter

    您可以像使用任何其他 NSFormatter 子类一样使用它。

    【讨论】:

    • 这种格式通用吗???我只是将 .h/.m 文件添加到我的项目中需要更多内容吗??
    【解决方案5】:

    非常感谢第一个答案,但我认为,-(int)getLength:(NSString*)mobileNumber 方法是没用的。您可以尝试以下方法:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    int length = [[self formatNumber:[textField text]] length];
    
    if (length == 10) {
        if(range.length == 0) {
            return NO;
        }
    }
    
    if (length == 3) {
        NSString *num = [self formatNumber:[textField text]];
        textField.text = [NSString stringWithFormat:@"(%@) ",num];
        if (range.length > 0) {
            [textField setText:[NSString stringWithFormat:@"%@",[num substringToIndex:3]]];
        }
    }
    else if (length == 6) {
        NSString *num = [self formatNumber:[textField text]];
        [textField setText:[NSString stringWithFormat:@"(%@) %@-",[num  substringToIndex:3],[num substringFromIndex:3]]];
        if (range.length > 0) {
            [textField setText:[NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]]];
        }
    }
    
    return YES;
    }
    
    - (NSString*)formatNumber:(NSString*)mobileNumber {
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
    mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
    
    int length = [mobileNumber length];
    
    if (length > 10) {
        mobileNumber = [mobileNumber substringFromIndex: length-10];
    }
    
    return mobileNumber;
    }
    

    【讨论】:

      【解决方案6】:

      对于那些需要国际号码格式的人:https://code.google.com/p/libphonenumber/

      带有 C++、Java 和 JavaScript 实现。应该很容易将 C++ 实现包装在 .mm 文件中,并在其周围编写一个小的 Objective-C 包装器。

      【讨论】:

      • 我试过这个并让它工作。不幸的是,C++ 库大约为 2 MB,它需要大约 40 MB 的依赖库。最大的依赖是 Unicode 库的国际组件,它本身大约有 35 MB,因为它包括“一个大小约为 16 MB 的标准数据库。其中大部分由转换表和语言环境信息组成。”所以这个解决方案对于 iOS 应用来说不是很实用。
      【解决方案7】:

      一个有效的选项是https://github.com/iziz/libPhoneNumber-iOS 所有其他答案仅涵盖一小部分可能性和组合,该库实际上解析和验证每个电话号码,并识别:

      • 国籍
      • 电话号码类型
      • 国家运营商

      【讨论】:

        【解决方案8】:

        与美国电话号码相关:

        添加到@wan 的帖子,如果用户以国家代码 (1) 开头,我添加了一个条件语句。这样,它将格式化为:1 (XXX) XXX-XXXX 而不是 (1XX) XXX-XXXX。

            - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
            textField = self.phoneNumberTextField;
        
            NSInteger length = [self getLength:textField.text];
            //NSLog(@"Length  =  %d ",length);
        
            if ([textField.text hasPrefix:@"1"]) {
                if(length == 11)
                {
                    if(range.length == 0)
                        return NO;
                }
                if(length == 4)
                {
                    NSString *num = [self formatNumber:textField.text];
                    textField.text = [NSString stringWithFormat:@"%@ (%@) ",[num substringToIndex:1],[num substringFromIndex:1]];
                    if(range.length > 0)
                        textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:4]];
                }
                else if(length == 7)
                {
                    NSString *num = [self formatNumber:textField.text];
                    NSRange numRange = NSMakeRange(1, 3);
                    textField.text = [NSString stringWithFormat:@"%@ (%@) %@-",[num substringToIndex:1] ,[num substringWithRange:numRange],[num substringFromIndex:4]];
                    if(range.length > 0)
                        textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
                }
        
            } else {
                if(length == 10)
                {
                    if(range.length == 0)
                        return NO;
                }
        
                if(length == 3)
                {
                    NSString *num = [self formatNumber:textField.text];
                    textField.text = [NSString stringWithFormat:@"(%@) ",num];
                    if(range.length > 0)
                        textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];
                }
                else if(length == 6)
                {
                    NSString *num = [self formatNumber:textField.text];
        
                    textField.text = [NSString stringWithFormat:@"(%@) %@-",[num  substringToIndex:3],[num substringFromIndex:3]];
                    if(range.length > 0)
                        textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
                }
            }
            return YES;
        }
        
        -(NSString*)formatNumber:(NSString*)mobileNumber
        {
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
        
            NSLog(@"%@", mobileNumber);
        
            NSInteger length = [mobileNumber length];
            if(length > 10)
            {
                mobileNumber = [mobileNumber substringFromIndex: length-10];
                NSLog(@"%@", mobileNumber);
        
            }
        
        
            return mobileNumber;
        }
        -(NSInteger)getLength:(NSString*)mobileNumber
        {
        
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
            mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
        
            NSInteger length = [mobileNumber length];
        
            return length;        
        }
        

        【讨论】:

          【解决方案9】:

          也许你可以使用这个简单的方法:

          + (NSString*) formatPhoneNumber:(NSString *)phoneNumber codeLength:(int) code segmentLength:(int) segment
          {
              NSString* result = @"";
          
              int length = [phoneNumber length];
          
              NSString* firstSegment = @"";
              NSString* restSegment = @"";
          
              for (int i=0; i<length; i++) {
          
                  char c = [phoneNumber characterAtIndex:i];
          
                  if(i < code)
                      firstSegment = [firstSegment stringByAppendingFormat:@"%c", c];
                  else
                  {
                      restSegment = [restSegment stringByAppendingFormat:@"%c", c];
          
                      int threshold = (i - code) + 1;
          
                      if((threshold % segment == 0) && (threshold > 0) && !(threshold > length))
                          restSegment = [restSegment stringByAppendingFormat:@"%c", '-'];
                  }
          
              }
          
              result = [result stringByAppendingFormat:@"%@-%@", firstSegment, restSegment];
          
              return result;
          }
          

          假设上面的方法在Contact类中,那么就使用这样的方法:

          NSString* phoneNumber = @"085755023455";
          
          NSString* formattedNumber = [Contact formatPhoneNumber:phoneNumber codeLength:3 segmentLength:4];
          

          这将导致类似:

          085-7550-2345-5
          

          【讨论】:

            【解决方案10】:

            您可以使用AKNumericFormatterlibrary。它具有格式化程序和方便的 UITextField 类别,可作为 cocoapod 使用。

            【讨论】:

              【解决方案11】:

              most comprehensive answer 的 C# Xamarin.iOS 版本在下面介绍如何在 iOS 中进行手机格式化

                  public override void ViewDidLoad()
                  {
                      base.ViewDidLoad();
                      PhoneNumberTextField.ShouldChangeCharacters = ChangeCharacters;
                  }
              
                  private bool ChangeCharacters(UITextField textField, NSRange range, string replacementString)
                  {
                      var text = textField.Text;
                      var newString = text.Substring(0, range.Location) + replacementString + text.Substring(range.Location + range.Length);
                      var decimalString = Regex.Replace(newString, @"[^\d]", string.Empty);
                      var length = decimalString.Length;
                      var hasLeadingOne = length > 0 && decimalString[0] == '1';
                      if ((length == 0) || (length > 10 && !hasLeadingOne) || (length > 11))
                      {
                          textField.Text = decimalString;
                          return false;
                      }
                      var index = 0;
                      var formattedString = "";
                      if (hasLeadingOne)
                      {
                          formattedString += "1";
                          index += 1;
                      }
                      if (length - index > 3)
                      {
                          var areaCode = decimalString.Substring(index, 3);
                          formattedString += "(" + areaCode + ")";
                          index += 3;
                      }
                      if (length - index > 3)
                      {
                          var prefix = decimalString.Substring(index, 3);
                          formattedString += " " + prefix + "-";
                          index += 3;
                      }
                      var remainder = decimalString.Substring(index);
                      formattedString += remainder;
                      textField.Text = formattedString;
                      return false;
                  }
              

              【讨论】:

                【解决方案12】:

                对于 +x (xxx) xxx-xx-xx 格式,您可以使用类似这样的简单解决方案:

                + (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
                NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
                NSArray *components = [newString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
                NSString *decimalString = [components componentsJoinedByString:@""];
                
                if (decimalString.length > 11) {
                    return NO;
                }
                
                NSMutableString *formattedString = [NSMutableString stringWithString:decimalString];
                
                [formattedString insertString:@"+" atIndex:0];
                
                if (formattedString.length > 2)
                    [formattedString insertString:@" (" atIndex:2];
                
                if (formattedString.length > 7)
                    [formattedString insertString:@") " atIndex:7];
                
                if (formattedString.length > 12)
                    [formattedString insertString:@"-" atIndex:12];
                
                if (formattedString.length > 15)
                    [formattedString insertString:@"-" atIndex:15];
                
                
                textField.text = formattedString;
                return NO;}      
                

                【讨论】:

                  【解决方案13】:

                  斯威夫特

                  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {        
                              let length = self.getTextLength(textField.text)
                              
                              
                              
                              if length == 10{
                                  if range.length == 0{
                                      return false
                                  }
                              }
                              
                              if length == 3{
                                  
                                  var num : String = self.formatNumber(textField.text)
                                  
                                  textField.text = num + "-"
                                  if(range.length > 0){
                                      textField.text = (num as NSString).substringToIndex(3)
                                  }
                              }
                              else if length == 6{
                                  
                                  var num : String = self.formatNumber(textField.text)
                                  
                                  let prefix  = (num as NSString).substringToIndex(3)
                                  let postfix = (num as NSString).substringFromIndex(3)
                                  
                                  textField.text = prefix + "-" + postfix + "-"
                                  
                                  if range.length > 0{
                                      textField.text = prefix + postfix
                                  }
                              }
                              
                              return true
                      }
                  
                  
                  
                  
                  func getTextLength(mobileNo: String) -> NSInteger{
                          
                          var str : NSString = mobileNo as NSString
                          str = str.stringByReplacingOccurrencesOfString("(", withString: "")
                          str = str.stringByReplacingOccurrencesOfString(")", withString: "")
                          str = str.stringByReplacingOccurrencesOfString(" ", withString: "")
                          str = str.stringByReplacingOccurrencesOfString("-", withString: "")
                          str = str.stringByReplacingOccurrencesOfString("+", withString: "")
                          
                          return str.length
                      }
                      
                      func formatNumber(mobileNo: String) -> String{
                          var str : NSString = mobileNo as NSString
                          str = str.stringByReplacingOccurrencesOfString("(", withString: "")
                          str = str.stringByReplacingOccurrencesOfString(")", withString: "")
                          str = str.stringByReplacingOccurrencesOfString(" ", withString: "")
                          str = str.stringByReplacingOccurrencesOfString("-", withString: "")
                          str = str.stringByReplacingOccurrencesOfString("+", withString: "")
                          
                          if str.length > 10{
                              str = str.substringFromIndex(str.length - 10)
                          }
                  
                          return str as String
                      }
                  

                  【讨论】:

                  • 显示 xxx-xx-xxxx 并询问 (xxx)-(xxx)-xxxx 的问题
                  【解决方案14】:

                  Swift 格式的电话号码

                  改进了@datinc 的回答, 输入如1123df#$@$gdfg45-+678dfg901 将输出为+11(234)567-8901

                  func formattedPhone(phone: String) -> String?  {
                      let notPhoneNumbers = NSCharacterSet.decimalDigitCharacterSet().invertedSet
                      let str = phone.componentsSeparatedByCharactersInSet(notPhoneNumbers).joinWithSeparator("")
                  
                      let startIdx = str.startIndex
                      let endIdx = str.endIndex
                  
                      let count = str.characters.count
                      if count == 7 {
                          return "\(str[startIdx..<startIdx.advancedBy(3)])-\(str[startIdx.advancedBy(3)..<endIdx])"
                      }else if count == 10{
                          return "(\(str[startIdx..<startIdx.advancedBy(3)]))\(str[startIdx.advancedBy(3)..<startIdx.advancedBy(6)])-\(str[startIdx.advancedBy(6)..<endIdx])"
                      }
                      else if count > 10{
                          let extra = str.characters.count - 10
                          return "+\(str[startIdx..<startIdx.advancedBy(extra)])(\(str[endIdx.advancedBy(-10)..<endIdx.advancedBy(-7)]))\(str[endIdx.advancedBy(-7)..<endIdx.advancedBy(-4)])-\(str[endIdx.advancedBy(-4)..<endIdx])"
                      }
                      return nil
                  }
                  

                  【讨论】:

                    【解决方案15】:

                    这对你有帮助

                    格式 (xxx) xxx-xxxx 适用于 SWIFT 3.0

                    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                            let length = Int(getLength(mobileNumber: textField.text!))
                    
                            if length == 15 {
                                if range.length == 0 {
                                    return false
                                }
                            }
                    
                            if length == 3 {
                    
                                let num = self.formatNumber(mobileNumber: textField.text!)
                    
                                textField.text = NSString(format:"(%@)",num) as String
                    
                                if range.length > 0{
                                    let index: String.Index = num.index(num.startIndex, offsetBy: 3)
                                    textField.text = NSString(format:"%@",num.substring(to: index)) as String
                                }
                    
                            }else if length == 6 {
                                let num = self.formatNumber(mobileNumber: textField.text!)
                                let index: String.Index = num.index(num.startIndex, offsetBy: 3)
                    
                                textField.text = NSString(format:"(%@) %@-",num.substring(to: index), num.substring(from: index)) as String
                                if range.length > 0{
                                    textField.text = NSString(format:"(%@) %@",num.substring(to: index), num.substring(from: index)) as String
                                }
                            }
                    
                            return true
                        }
                    
                        func formatNumber(mobileNumber: String) -> String {
                            var number = mobileNumber
                            number = number.replacingOccurrences(of: "(", with: "")
                            number = number.replacingOccurrences(of: ")", with: "")
                            number = number.replacingOccurrences(of: " ", with: "")
                            number = number.replacingOccurrences(of: "-", with: "")
                            number = number.replacingOccurrences(of: "+", with: "")
                    
                            let length = Int(number.characters.count)
                    
                            if length > 15 {
                                let index = number.index(number.startIndex, offsetBy: 15)
                    
                               number = number.substring(to: index)
                            }
                    
                            return number
                        }
                    
                        func getLength(mobileNumber: String) -> Int {
                    
                            var number = mobileNumber
                            number = number.replacingOccurrences(of: "(", with: "")
                            number = number.replacingOccurrences(of: ")", with: "")
                            number = number.replacingOccurrences(of: " ", with: "")
                            number = number.replacingOccurrences(of: "-", with: "")
                            number = number.replacingOccurrences(of: "+", with: "")
                    
                            let length = Int(number.characters.count)
                            return length
                    
                        }
                    

                    【讨论】:

                      【解决方案16】:
                      NSString *str=@"[+]+91[0-9]{10}";
                      NSPredicate *no=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",str];
                      if([no evaluateWithObject:txtMobileno.text]==NO
                      { 
                          UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Please Enter correct contact no." delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
                      
                          [alert show];
                          [alert release];    
                      }
                      

                      【讨论】:

                        【解决方案17】:

                        所以这个方法将格式化为 (xxx) xxx - xxxx ....
                        它是对当前最佳答案的修改并处理退格

                        - (IBAction)autoFormat:(UITextField *)sender {
                        
                        NSString *mobileNumber = [NSString stringWithFormat:@"%@",sender.text];
                        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
                        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
                        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
                        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
                        mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
                        
                        int length = [mobileNumber length];
                        if(length > 0 && [sender.text length] > self.oldLength){
                            if(length >= 7 && length <= 10){
                                sender.text = [NSString stringWithFormat:@"(%@) %@ - %@",[mobileNumber substringToIndex:3], [mobileNumber substringWithRange:NSMakeRange(3,3)],[mobileNumber substringWithRange:NSMakeRange(6,[mobileNumber length]-6)]];
                            } else if(length >= 4 && length <= 6) {
                                sender.text = [NSString stringWithFormat:@"(%@) %@",[mobileNumber substringToIndex:3], [mobileNumber substringWithRange:NSMakeRange(3,[mobileNumber length]-3)]];
                            }
                            if(length >= 11 && length % 4 == 3){
                                NSString *lastChar = [sender.text substringFromIndex:[sender.text length] - 1];
                                sender.text = [NSString stringWithFormat:@"%@ %@",[sender.text substringToIndex:[sender.text length] - 1],lastChar];
                            }
                            self.oldLength = [sender.text length];
                        } else if([sender.text length] < self.oldLength) {
                            NSLog(@"deleted - ");
                            self.oldLength = 0;
                        
                            sender.text = @"";
                            for (int i = 0; i < [mobileNumber length]; i = i + 1) {
                                sender.text = [NSString stringWithFormat:@"%@%@",sender.text,[mobileNumber substringWithRange:NSMakeRange(i, 1)]];
                                [self autoFormat:sender];
                            }
                        }}
                        

                        希望对你有帮助

                        【讨论】:

                          【解决方案18】:

                          REFormattedNumberField 可能是最好的。只需提供您希望的格式即可。

                          【讨论】:

                            【解决方案19】:
                            +(NSString *) phoneNumberFormatterTextField:(NSString *)number forRange:(NSRange)range
                            {
                                int length = (int)[[self getPhoneNumber:number] length];
                                if(length == 3)
                                {
                                    NSString *num = [MPosBaseScreenController getPhoneNumber:number];
                                    number = [num stringByReplacingOccurrencesOfString:@"(\\d{3})"
                                                                          withString:@"($1) "
                                                                             options:NSRegularExpressionSearch
                                                                               range:NSMakeRange(0, num.length)];
                            
                                }
                                else if(length == 6 || length > 6 )
                                {
                                    NSString *num = [MPosBaseScreenController getPhoneNumber:number];
                                    number = [num stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d{3})"
                                                                          withString:@"($1) $2 - "
                                                                             options:NSRegularExpressionSearch
                                                                               range:NSMakeRange(0, num.length)];
                                }
                                   return number;
                            }
                            

                            【讨论】:

                              【解决方案20】:

                              这是一个模拟输入格式的简单类别

                              @interface NSString (formatDecimalsAs)
                              - (NSString *)formatDecimalsAs:(NSString *)formattedDecimals;
                              @end
                              
                              @implementation NSString (formatDecimalsAs)
                              - (NSString *)formatDecimalsAs:(NSString *)formattedDecimals
                              {
                                  // insert non-digit characters from source string
                                  NSMutableString *formattedNumber = [self mutableCopy];
                                  for (int i = 0; i < formattedDecimals.length; i++)
                                  {
                                      if (i > formattedNumber.length)
                                      {
                                          break;
                                      }
                                      unichar character = [formattedDecimals characterAtIndex:i];
                                      if ([[NSCharacterSet decimalDigitCharacterSet].invertedSet characterIsMember:character])
                                      {
                                          [formattedNumber insertString:[NSString stringWithFormat:@"%c", character] atIndex:(NSUInteger) i];
                                      }
                                  }
                                  return formattedNumber;
                              }
                              @end
                              

                              示例使用

                              [@"87654321" formatDecimalsAs:@"1111 1111"] // returns @"8765 4321"
                              

                              【讨论】:

                                【解决方案21】:
                                1. 删除所有非数字字符
                                2. 如果还剩 7 位数,则为 123-4567
                                3. 10 位数,(123) 456-7890
                                4. 否则,三人一组。要调整组的大小,请更改分配给 substrsize 的值

                                  -(NSString*)formatPhone:(NSString*)phone {
                                  
                                       NSString *formattedNumber = [[phone componentsSeparatedByCharactersInSet:
                                                            [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                                                           componentsJoinedByString:@""];
                                  
                                  int substrSize = 3;
                                  NSMutableArray *t = [[NSMutableArray alloc] initWithCapacity:formattedNumber.length / substrSize + 1];
                                  switch (formattedNumber.length) {
                                      case 7:
                                          formattedNumber = [NSString stringWithFormat:@"%@-%@",
                                                         [formattedNumber substringToIndex:3],
                                                         [formattedNumber substringFromIndex:3]];
                                      break;
                                  
                                      case 10:
                                          formattedNumber = [NSString stringWithFormat:@"(%@) %@-%@",
                                                         [formattedNumber substringToIndex:3],
                                                         [formattedNumber substringWithRange:NSMakeRange(3, 3)],
                                                         [formattedNumber substringFromIndex:6]];
                                      break;
                                  
                                      default:
                                          for (int i = 0; i < formattedNumber.length / substrSize; i++) {
                                          [t addObject:[formattedNumber substringWithRange:NSMakeRange(i * substrSize, substrSize)]];
                                          }
                                          if (formattedNumber.length % substrSize) {
                                              [t addObject:[formattedNumber substringFromIndex:(substrSize * t.count)]];
                                      }
                                          formattedNumber = [t componentsJoinedByString:@" "];
                                      break;
                                   }
                                   return formattedNumber;
                                  }
                                  

                                【讨论】:

                                • 不错的代码示例!你能详细说明它的作用吗?
                                【解决方案22】:

                                SWIFT 3

                                func formattedPhone(phone: String) -> String?  {
                                    let notPhoneNumbers = CharacterSet.decimalDigits.inverted
                                    let str = phone.components(separatedBy: notPhoneNumbers).joined(separator: "")
                                
                                    let startIdx = str.startIndex
                                    let endIdx = str.endIndex
                                
                                    let count = str.characters.count
                                    if count == 7 {
                                        return "\(str[startIdx..<startIdx.advance(3, for: str)])-\(str[startIdx.advance(3, for: str)..<endIdx])"
                                    }else if count == 10{
                                        return "+1 (\(str[startIdx..<startIdx.advance(3, for: str)])) \(str[startIdx.advance(3, for: str)..<startIdx.advance(6, for: str)])-\(str[startIdx.advance(6, for: str)..<endIdx])"
                                    }
                                    else if count > 10{
                                        let extra = str.characters.count - 10
                                        return "+\(str[startIdx..<startIdx.advance(extra, for: str)]) (\(str[endIdx.advance(-10, for: str)..<endIdx.advance(-7, for: str)])) \(str[endIdx.advance(-7, for: str)..<endIdx.advance(-4, for: str)])-\(str[endIdx.advance(-4, for: str)..<endIdx])"
                                    }
                                    return nil
                                }
                                

                                Swift 3 string.index.advancedBy(3) 备用:

                                extension String.Index{
                                func advance(_ offset:Int, `for` string:String)->String.Index{
                                    return string.index(self, offsetBy: offset)
                                }
                                }
                                

                                【讨论】:

                                  【解决方案23】:

                                  首先,将UITextFieldDelegate 添加到您的.h 文件并在nib 文件中委托您的UITextField

                                  其次,将此代码添加到您的.m 文件中:

                                      - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
                                          {
                                              NSString *filter = @"(###)-(###)-####";
                                  
                                              if(!filter) return YES;
                                  
                                              NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
                                  
                                              if(range.length == 1 && 
                                                 string.length < range.length &&
                                                 [[textField.text substringWithRange:range] rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]].location == NSNotFound)
                                              {
                                  
                                                  NSInteger location = changedString.length-1;
                                                  if(location > 0)
                                                  {
                                                      for(; location > 0; location--)
                                                      {
                                                          if(isdigit([changedString characterAtIndex:location]))
                                                          {
                                                              break;
                                                          }
                                                      }
                                                      changedString = [changedString substringToIndex:location];
                                                  }
                                              }
                                  
                                              textField.text = [self filteredPhoneStringFromStringWithFilter:changedString :filter];
                                  
                                              return NO;
                                  
                                          }
                                  
                                      -(NSString*) filteredPhoneStringFromStringWithFilter:(NSString*)number : (NSString*)filter{
                                          NSUInteger onOriginal = 0, onFilter = 0, onOutput = 0;
                                          char outputString[([filter length])];
                                          BOOL done = NO;
                                  
                                      while(onFilter < [filter length] && !done)
                                      {
                                          char filterChar = [filter characterAtIndex:onFilter];
                                          char originalChar = onOriginal >= number.length ? '\0' : [number characterAtIndex:onOriginal];
                                          switch (filterChar) {
                                              case '#':
                                                  if(originalChar=='\0')
                                                  {
                                                      // We have no more input numbers for the filter.  We're done.
                                                      done = YES;
                                                      break;
                                                  }
                                                  if(isdigit(originalChar))
                                                  {
                                                      outputString[onOutput] = originalChar;
                                                      onOriginal++;
                                                      onFilter++;
                                                      onOutput++;
                                                  }
                                                  else
                                                  {
                                                      onOriginal++;
                                                  }
                                                  break;
                                              default:
                                                  // Any other character will automatically be inserted for the user as they type (spaces, - etc..) or deleted as they delete if there are more numbers to come.
                                                  outputString[onOutput] = filterChar;
                                                  onOutput++;
                                                  onFilter++;
                                                  if(originalChar == filterChar)
                                                      onOriginal++;
                                                  break;
                                          }
                                      }
                                      outputString[onOutput] = '\0'; // Cap the output string
                                      return [NSString stringWithUTF8String:outputString];
                                  }
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 2014-04-01
                                    • 2010-12-31
                                    • 1970-01-01
                                    • 2023-03-27
                                    • 2013-02-05
                                    • 2012-08-11
                                    • 2012-07-16
                                    • 2016-05-04
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多