1,通过attributedText设置,而且attributedText是可以append操作,这种可用于多个不同不行的text相连的操作,如下:
let scoretext = NSLocalizedString("my_score_title",comment:"")
let textAttr = NSAttributedString(string: scoretext, attributes: nil)
let scoreAttr = NSAttributedString(string: (data.score)!, attributes: [NSAttributedStringKey.foregroundColor:UIColor(255, 132, 41)])
let mutattr = NSMutableAttributedString(attributedString: textAttr)
mutattr.append(scoreAttr)
myScoreLabel.attributedText = mutattr
2,一段文字中间某部分文字,设置不同的属性,这个是需要通过range来操作
//color and underline
let dicattrs:Dictionary<NSAttributedStringKey,Any>=[NSAttributedStringKey.underlineStyle:0x01,NSAttributedStringKey.foregroundColor:UIColor(72, 199, 252)];
termAndprivacyContent.addAttributes(dicattrs, range: nsRangeTerm!)
termAndprivacyContent.addAttributes(dicattrs, range: nsRangePrivacy!)
termprivacy.attributedText = termAndprivacyContent
3,文字+图片的样式
let text = (liveinfo.username)! + " "
let attch = NSTextAttachment()
if (liveinfo.gender)! == GenderType.male.rawValue{
attch.image = #imageLiteral(resourceName: "male")
}else{
attch.image = #imageLiteral(resourceName: "female")
}
attch.bounds = CGRect(x:0,y:-2,width:32,height:32)
let imageAttr = NSAttributedString.init(attachment: attch)
let textAttr = NSAttributedString.init(string: text, attributes: nil)
let mutattr = NSMutableAttributedString.init(attributedString: textAttr)
mutattr.append(imageAttr)
anchorNameLabel.attributedText = mutattr
网友评论