使用属性文本修改下划线的宽度?

时间:2015-07-27 23:42:47

标签: ios objective-c nsstring nsattributedstring

有没有办法修改下划线和NSAttributedString的线宽?

我似乎可以轻松修改颜色,但我无法轻易修改下划线本身的宽度。

2 个答案:

答案 0 :(得分:3)

您可以设置NSUnderlineStyleThickNSUnderlineStyleSingle,例如:

NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Thick underline" attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleThick)}];
NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Normal underline" attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}];

下划线样式的完整列表:https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/NSAttributedString_UIKit_Additions/index.html#//apple_ref/c/tdef/NSUnderlineStyle

答案 1 :(得分:1)

//假设Label name为“label”

//下划线代码

CGSize expectedLabelSize = [@"Some text" sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:UILineBreakModeWordWrap];

UIView *viewForUnderline=[[UIView alloc] init];
viewForUnderline.frame=CGRectMake((label.frame.size.width - expectedLabelSize.width)/2,    expectedLabelSize.height + (label.frame.size.height - expectedLabelSize.height)/2,   expectedLabelSize.width, 1);
viewForUnderline.backgroundColor=[UIColor whiteColor];
[self.view addSubview:viewForUnderline];

或者您可以使用以下代码行

label.attributedText = [[NSAttributedString alloc] initWithString:@"Some Text" 
                                                     attributes:underlineAttribute];