app開發(fā)場(chǎng)景中,經(jīng)常會(huì)使用到富文本,常規(guī)做法使用NSMutableAttributedString設(shè)置
OC版本代碼
NSMutableAttributedString * remindAttri = [[NSMutableAttributedString alloc] initWithString:@"我已閱讀并同意《服務(wù)協(xié)議》"];
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 = "我已閱讀并同意《服務(wù)協(xié)議》"
let attribute = NSMutableAttributedString(string: agreeString)
let range = NSRange(location: 5, length: 6)
//設(shè)置顏色
attribute.addAttributes([NSAttributedStringKey.strokeColor:UIColor.orange], range: range)
//設(shè)置鏈接
attribute.addAttributes([NSAttributedStringKey.link:"http://www.baidu.com"], range: range)
效果如圖:

1527844163347.jpg
明明是設(shè)置的其他顏色,然后開始調(diào)試,注釋掉設(shè)置跳轉(zhuǎn)鏈接代碼,看看效果

1527844133084.jpg
只要設(shè)置跳轉(zhuǎn)鏈接就會(huì)覆蓋顏色,最后不折騰了,選擇一個(gè)成熟的第三方框架
YYText,使用方法如下:
let agreeLabelAttri = NSMutableAttributedString(string:agreeLabelText)
//設(shè)置文本size
agreeLabelAttri.yy_setTextHighlight(NSRange(location: 9, length: 10), color: UIColor.red, backgroundColor: UIColor.clear) { (containView, text, range, rect) in
print("點(diǎn)擊了協(xié)議進(jìn)行跳轉(zhuǎn)")
}
//為文本設(shè)置屬性
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
效果如下:

1527844716903.jpg
這種功能還是使用成熟的第三方框架更方便,自己實(shí)現(xiàn),還是有一些坑的,swift還有很長(zhǎng)的路要走啊