Akshay Ambekar Akshay Ambekar - 5 months ago 37
Objective-C Question

How to assign UIcolor to NSString?

I have array of dictionary

[
{
"price": 0,
"test_name": "Multislice CT Scan Virtual Bronchoscopy"
},
{
"price": 0,
"test_name": "Multislice CT Scan Dental"
},
{
"price": 0,
"test_name": "Multislice CT Scan Joint (3D)"
},
{
"price": 0,
"test_name": "Multislice CT Scan Lumbar"
},
{
"price": 0,
"test_name": "Multislice CT Scan Spine - Cervical / Thoracic"
},
{
"price": 0,
"test_name": "Multislice CT Scan CT Urography"
},


And am converting this array of dictionary to nsstring like by appending \n at the end of each dictionary value

Multislice CT Scan Virtual Bronchoscopy
Rs.0

Multislice CT Scan Dental
Rs.0

Multislice CT Scan Joint (3D)
Rs.0

Multislice CT Scan Lumbar
Rs.0

Multislice CT Scan Spine - Cervical / Thoracic
Rs.0

Multislice CT Scan CT Urography
Rs.0

Multislice CT Scan (Arterial + Portal + Venous)
Rs.0

Multislice CT Scan Abdomen Triphasic Lever
Rs.0


And now I want Rs.0 string in redColor... How to give red color to that specific string???

Am using static table.. in that am assigning this whole string to single label..

Answer

Try something like this using this your all Rs.0 will be display as Red color

NSString *str = @"Multislice CT Scan Virtual Bronchoscopy Rs.0 Multislice CT Scan Dental Rs.0";

NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:str];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(Rs.[0-9]*)" options:kNilOptions error:nil];

NSRange range = NSMakeRange(0,strFirst.length);

[regex enumerateMatchesInString:strFirst options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:1];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];
}];
self.label.attributedText = attributedString;

Hope this will help you.