我尝试使用自定义字体( HelveticaRounded-Bold )为属性文本添加下划线。然而,模拟器和设备上的下划线都出现了问题。像这样:
这是UILabel
,但我也可以在UITextView
中重现该问题。看起来好像文本渲染器错误地计算了在某些行上绘制下划线的位置。
简单的代码:
- (void)viewDidLoad {
[super viewDidLoad];
UIFont *font = [UIFont fontWithName:@"HelveticaRounded-Bold" size:18];
self.label.font = font;
self.label.numberOfLines = 0;
NSDictionary *attributes = @{ NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) };
self.label.attributedText = [[NSAttributedString alloc] initWithString:@"This is a test. And the test has failed. What did I do to deserve this? Why NSUnderlineStyleAttributeName? Why?"
attributes:attributes];
}
有趣的事实:下划线在24或以上(!)时不会出现故障。它也不会使用TTTAttributedLabel
重新编译。
知道这里可能会发生什么吗?
答案 0 :(得分:0)
使用NSUnderlineStyleThick
时,非视网膜设备似乎是一个小问题。切换到NSUnderlineStyleSingle
似乎可以解决问题。因此,如果要将NSUnderlineStyleSingle
保留在其他设备上,则可以为非视网膜设备设置条件以使用NSUnderlineStyleThick
。
编辑:刚刚意识到您在示例代码中使用了NSUnderlineStyleSingle
:/在我的代码中,这适用于我给定的字体/大小,这只是系统字体。这解决了我的问题。因此,似乎这个修复可能不是通用的,但它在我的情况下起作用。
答案 1 :(得分:0)
在非视网膜显示器上,UIButton出现了相同的问题。我所做的只是将非视网膜设备的“ NSUnderlineStyleSingle”更改为“ NSUnderlineStyleDouble”。
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleString?titleString:@"" attributes:@{ NSFontAttributeName: button.titleLabel.font}];
[buttonTitleString addAttribute:NSUnderlineStyleAttributeName value:[CommonUtil getValueForUnderlineStyle] range:NSMakeRange(0, [buttonTitleString length])];
[button.titleLabel setAttributedText:attributedString];
+ (NSNumber *)getValueForUnderlineStyle {
NSNumber *numberToReturn = @(NSUnderlineStyleSingle);
if(!(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && [[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [UIScreen mainScreen].scale > 1)) {
// Non Retina iPad
numberToReturn = @(NSUnderlineStyleDouble);
}
return numberToReturn;
}