Wednesday, 26 June 2013

Single UILabel with different color text and fonts possible?


Yes, Its possible in to have different colored text and fonts in single UILabel, from iOS6 onwards using "NSMutableAttributedString".

-(void)AttributedTextInUILabelWithGreenText:(NSString *)greenText withYellowText:(NSString *) yellowText withBlueBoldText:(NSString *)blueBoldText
{
    NSString *text = [NSString stringWithFormat:@"Here are %@, %@ and %@",
                      greenText,
                      yellowText,
                      blueBoldText];

    //Check If attributed text is unsupported (below iOS6+)
    if (![self.label respondsToSelector:@selector(setAttributedText:)]) {   
     self.label.text = text;
    }
    // If attributed text is available
    else {
        // Define general attributes like color and fonts for the entire text
        NSDictionary *attribs = @{
                                  NSForegroundColorAttributeName: self.label.textColor,
                                  NSFontAttributeName: self.label.font
                                  };
        NSMutableAttributedString *attributedText =
        [[NSMutableAttributedString alloc] initWithString:text
                                               attributes:attribs];

        // green text attributes
        UIColor *greenColor = [UIColor greenColor];
        NSRange greenTextRange = [text rangeOfString:redText];
        [attributedText setAttributes:@{NSForegroundColorAttributeName:greenColor}
                                range:greenTextRange];

        // yellow text attributes
        UIColor *yellowColor = [UIColor yellowColor];
        NSRange yellowTextRange = [text rangeOfString:greenText];
        [attributedText setAttributes:@{NSForegroundColorAttributeName:yellowColor}
                                range:yellowTextRange];

        // blue and bold text attributes
        UIColor *blueColor = [UIColor blueColor];
        UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
        NSRange blueBoldTextRange = [text rangeOfString:blueBoldText];
        [attributedText setAttributes:@{NSForegroundColorAttributeName:blueColor,
                  NSFontAttributeName:boldFont}
                                range:blueBoldTextRange];
        self.label.attributedText = attributedText;
        
}

No comments:

Post a Comment