Search code examples
objective-cios6uibuttonnsattributedstring

UIButton setAttributedTitle: forState: Not Showing Up


I am trying to add underlining to my title on a custom UIButton but by following the example found here, I can't get it to show on the screen.

Here is the code I am trying to use:

NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"The Quick Brown Fox"];

[commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];

[button setAttributedTitle:commentString forState:UIControlStateNormal];

This doesn't show up. But if I just do a regular one, like so:

[button setTitle:@"The Quick Brown Fox" forState:UIControlStateNormal];

This shows up fine. Can someone tell me what I am missing?


Solution

  • I realized the problem here. I assumed that it was not showing up because I could not see it. However, it was showing up, it is just the same color as the background.

    I wrongly assumed that [button setTitleColor:myColor forState:UIControlStateNormal]; would be the color that the attributedTitle would use as well. However, my background is black and the NSMutableAttributedString must default to black.

    [commentString addAttribute:NSForegroundColorAttributeName value:myColor  range:NSMakeRange(0, [commentString length])];
    

    Makes it show up correctly.