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\"
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 :)