UILabel:自定义下划线颜色?

nin*_*eer 10 nsattributedstring uilabel ios ios7 tttattributedlabel

我需要a的文本UILabel是黑色的,但在文本下面有一个浅灰色的下划线.是否可以使用NSAttributedStringTTTAttributedLabel?或者是否需要使用Core Graphics的自定义绘图?

澄清:我需要一个不同颜色下划线的特定颜色文本.示例:红色下划线上的蓝色文本.

Man*_*ani 20

你可以这样做NSAttributedString.

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;
Run Code Online (Sandbox Code Playgroud)

注意:您也可以在此帖子中为特定范围的字符串加下划线.另请注意,它仅适用于ios6 +.


Oha*_*adM 5

NSMutableAttributedString我们总是可以在一行中(使用 NSDictionary 符号 - @ { })为包含实际文本的特定UILabel创建多个属性,而不是创建一个本地并一个一个地添加属性。

目标C

[someUILabel setAttributedText:
  [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", [someObject stringProperty]]
                                  attributes:@{NSUnderlineStyleAttributeName:@(NSUnderlineStyleThick),
                                              NSUnderlineColorAttributeName:[[UIColor alloc] initWithRed:0.953f green:0.424f blue:0.416f alpha:1.00f]}]];
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我们设置了一个粗体的下划线 - 总共 2 个属性。

斯威夫特

self.someUIButton.setAttributedTitle(NSAttributedString(string: "UIButtonStringTitle", attributes: [NSUnderlineStyleAttributeName : 1]), forState: .Normal)
Run Code Online (Sandbox Code Playgroud)