Search code examples
iosios7uilabelnsattributedstringtttattributedlabel

UILabel: Custom underline color?


I need the text of a UILabel to be black, but have a light gray underline under the text. Is this possible with NSAttributedString or TTTAttributedLabel? Or is custom drawing using Core Graphics needed?

CLARIFICATION: I need a specific color text on a different color underline. Example: blue text on red underline.


Solution

  • You can do with NSAttributedString as below.

    NSMutableAttributedString* string = [[NSMutableAttributedString alloc]initWithString:@"you string"];
    [string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, string.length)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length)];//TextColor
    [string addAttribute:NSUnderlineStyleAttributeName value:underlineNumber range:NSMakeRange(0, string.length)];//Underline color
    [string addAttribute:NSUnderlineColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, string.length)];//TextColor
     yourlabel. attributedText = string;
    

    Note: You can also underline particular range of string as like in this post. Also note down, it works ios6+ only.