app开发场景中,经常会使用到富文本,常规做法使用NSMutableAttributedString设置
OC版本代码
NSMutableAttributedString * remindAttri = [[NSMutableAttributedString alloc] initWithString:@"我已阅读并同意《服务协议》"];
NSRange remindRange = NSMakeRange(remindAttri.length-6, 6);
[remindAttri addAttribute:NSLinkAttributeName value:[NSURL URLWithString:[NSString stringWithFormat:@"%@",BRH_URL_PROTOCOL]] range:remindRange];
[remindAttri addAttribute:NSStrokeColorAttributeName value:red_Color range:remindRange];
self.remindLab.attributedText = remindAttri;
swift版本代码
let agreeString = "我已阅读并同意《服务协议》"
let attribute = NSMutableAttributedString(string: agreeString)
let range = NSRange(location: 5, length: 6)
//设置颜色
attribute.addAttributes([NSAttributedStringKey.strokeColor:UIColor.orange], range: range)
//设置链接
attribute.addAttributes([NSAttributedStringKey.link:"http://www.baidu.com"], range: range)
效果如图:
明明是设置的其他颜色,然后开始调试,注释掉设置跳转链接代码,看看效果
只要设置跳转链接就会覆盖颜色,最后不折腾了,选择一个成熟的第三方框架
YYText,使用方法如下:
let agreeLabelAttri = NSMutableAttributedString(string:agreeLabelText)
//设置文本size
agreeLabelAttri.yy_setTextHighlight(NSRange(location: 9, length: 10), color: UIColor.red, backgroundColor: UIColor.clear) { (containView, text, range, rect) in
print("点击了协议进行跳转")
}
//为文本设置属性
agreeLabelAttri.yy_font = UIFont.systemFont(ofSize: 14)
agreeLabelAttri.yy_color = UIColor.hexStringToColor(hexString: "9DA4B3")
agreeLabelAttri.yy_setColor(UIColor.hexStringToColor(hexString: "FE2E3B"), range: NSRange(location: 9, length: 10))
agreeLabel.attributedText = agreeLabelAttri
效果如下:
这种功能还是使用成熟的第三方框架更方便,自己实现,还是有一些坑的,swift还有很长的路要走啊