Wednesday, March 30, 2016

How to change the color or font style of a word or a character within a single UILabel?

In iOS, usually while displaying a heading or topic name or any sort of text within our app, we generally assign our string to a UILabel. 
But suppose what if, If we have a requirement like if you want to highlight a particular word or letter in between a single string or what if you want to change color of a specific character or a word in between a string?
Do you add multiple UILabel's to achieve this?, Isn't that sounds weird? of-course right :), so what is the best approach to achieve this then?
Here is a solution, by using NSMutableAttributedString you can achieve this just by using one single UILabel.

In the below example I have created a category method for NSMutableAttributedString, since the scope of this highlighting method will be existing throughout my application, if you need this in only one place then go and create an instance method within your implementation class, its up to you.


My NSMutableAttributedString category method is like below,
- (void)highlightText:(NSString *)highlightString withFont:(UIFont *)font andColor:(UIColor *)color
{
    NSRange range = [self.mutableString rangeOfString:highlightString options:NSCaseInsensitiveSearch];
    
    if (range.location != NSNotFound)
    {
        [self addAttribute:NSFontAttributeName value:font range:range];
        [self addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
}
and in my calling class I can just call this category method and pass the specific word or letter which needs to be highlighted to this method with required style and color as a parameters and my job is done.
Here in the below example, I am highlighting “iOS” and “Apple” word in my string with different font style and color, so my calling class code snippet is like below,

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"iOS is Apple's mobile OS"];
    [attributedString highlightText:@"iOS" withFont:[UIFont fontWithName:@"AmericanTypewriter-Bold" size:25.0] andColor:[UIColor redColor]];
    [attributedString highlightText:@"Apple" withFont:[UIFont fontWithName:@"Georgia" size:35.0] andColor:[UIColor greenColor]];
    _attributedLabel.attributedText = attributedString;

and the output of this is as below,
Reference screenshot for NSAttributedString


For more information on this refer Apple's official documentation here,

Hope this post is helpful, any comments or suggestions are acceptable.