Wednesday 11 February 2015

How to set multiple color and multiple font for single uilable text?

Here I used two variables as a two different string and combined that string in to one string variable and then assign to UILable, after that I define NSFont variables as well as NSMutableAttributedString and set different property for that objects and after assign that modified attribute string to the UILable text.


    NSString *strCombineMessage = @"";
    strCombineMessage = [NSString stringWithFormat:@"%@ : %@",strUsername,strMessage];

    UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:14.0];
    UIFont *secondFont = [UIFont fontWithName:@"Helvetica-Oblique" size:14.0];
    
    self.lblMessage.text = strCombineMessage;
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.lblMessage.text];
    
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:23.0/255.0 green:163.0/255.0 blue:181.0/255.0 alpha:1] range:[self
                                                                                                                                           .lblMessage.text rangeOfString:strUsername]];
    [str addAttribute:NSFontAttributeName value:font range:[self
                                                            .lblMessage.text rangeOfString:strUsername]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:[self
                                                                                       .lblMessage.text rangeOfString:strMessage]];
    [str addAttribute:NSFontAttributeName value:secondFont range:[self
                                                                  .lblMessage.text rangeOfString:strMessage]];
    

    self.lblMessage.attributedText = str;


Here you have different type of property availble for NSMutableAttributedString for ex. NSForegroundColorAttributeName, NSFontAttributeName,etc....