How to change colour of all numbers in a string in swift

前端 未结 6 817
灰色年华
灰色年华 2021-01-14 11:24

I am trying to change colour for all numbers present in a string in swift code.Example:

var mystring = \"abc 3423 opqrs 474598 lmno 343543\"
         


        
6条回答
  •  生来不讨喜
    2021-01-14 11:58

    I am not much familiar with swift but i have try to make demo in objective c and it's works fine as your requirement if it can help,

      NSString *str = @"abc 3423 opqrs 474598 lmno 343543";
    
    NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc]initWithString:@"abc 3423 opqrs 474598 lmno 343543"];
    
    NSArray *arr = [str componentsSeparatedByString:@" "];
    
    for (int i = 0; i < arr.count; i++) {
    
    
        NSString *temp = [arr objectAtIndex:i];
    
        NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        if ([temp rangeOfCharacterFromSet:notDigits].location == NSNotFound)
        {
            NSDictionary *attrs = @{
    
                                    NSForegroundColorAttributeName:[UIColor redColor]
                                    };
    
            NSRange range = [str rangeOfString:[arr objectAtIndex:i]];
    
            [str1 addAttributes:attrs range:range];
        }
    
    
    }
    
    UILabel *temp = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 300, 50)];
    
    [self.view addSubview:temp];
    
    temp.attributedText = str1;
    

    You can use logic and concept and can use in swift as your requirement.

    Hope this will help :)

提交回复
热议问题