在开发中由于需要对button的文字添加下划线,所以采用富文本形式进行设置
- (UIButton *)goDetailButton {
if (!_goDetailButton) {
_goDetailButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_goDetailButton addTarget:self action:@selector(goDetailButtonAction)];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"去详情页"];
NSRange strRange = {0,[str length]};
[str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
[_goDetailButton setAttributedTitle:str forState:UIControlStateNormal];
_goDetailButton.titleLabel.font = [UIFont systemFontOfSize:12];
[_goDetailButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
}
return _goDetailButton;
}
一开始在富文本没有设置颜色那么富文本的默认颜色肯定是黑色,然后下面设置了title属性的颜色,在iOS14的版本下显示的确实是title设置的颜色,但是在11老系统的情况下这个富文本就是黑色.
所以最终采用全部使用富文本设置颜色,而不是用title属性设置的颜色.
[self.goDetailButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
- (UIButton *)goDetailButton {
if (!_goDetailButton) {
_goDetailButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_goDetailButton addTarget:self action:@selector(goDetailButtonAction)];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"去详情页"];
NSRange strRange = {0,[str length]};
[str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]range:strRange];
[_goDetailButton setAttributedTitle:str forState:UIControlStateNormal];
_goDetailButton.titleLabel.font = [UIFont systemFontOfSize:12];
}
return _goDetailButton;
}
总结: 富文本的颜色与label属性的颜色在某些版本下存在冲突.建议在使用富文本的时候,只对富文本设置颜色
网友评论