UILabel: Custom underline color?

前端 未结 5 1930
谎友^
谎友^ 2021-01-02 03:22

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 TTTAttr

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 03:52

    // Print `str` in black, and underline the word STRING in gray.
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"This is my STRING"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, str.length-7)];
    [str addAttribute:NSUnderlineColorAttributeName value:[UIColor grayColor] range:NSMakeRange([str length]-6, 6)];
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange([str length]-6, 6)];
    
    _label.attributedText = str; // assuming you have an iVar name `label`
    

提交回复
热议问题