基于swift4.1写了个简单富文本的实现例子,如有其它需求可在NSAttributedStringKey后面更改相应的属性
func transformContentText() -> NSMutableAttributedString {
let name:String = "胖虎";
let content:String = ":你特么是在刁难我胖虎么";
let str:String = name + content
let attributedStr = NSMutableAttributedString.init(string: str)
attributedStr.addAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14)], range: NSMakeRange(0, str.count))
attributedStr.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.nameColor], range: NSMakeRange(0, name.count))
attributedStr.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.green], range: NSMakeRange(name.count, content.count))
return attributedStr
}
网友评论