Snip20170527_17.png
step one
let attrStr1 = NSAttributedString(string: "爱你", attributes: [NSForegroundColorAttributeName : UIColor.red])
let attrStr2 = NSAttributedString(string: "我的宝贝", attributes: [NSForegroundColorAttributeName : UIColor.blue])
step two
//创建NSTextAttachment对象
let attachment = NSTextAttachment()
//给NSTextAttachment 对象设置图片
attachment.image = UIImage(named: "d_aini")
//设置NSTextAttachment对象的位置 目的是要图片和UILabel的高度一致
let font = demoLabel.font
attachment.bounds = CGRect(x: 0, y: -4, width: (font?.lineHeight)!, height: (font?.lineHeight)!)
//给富文本赋值
let attrImage = NSAttributedString(attachment: attachment)
step three
let attrMub = NSMutableAttributedString()
//给可变的富文本对象赋值
attrMub.append(attrStr1)
attrMub.append(attrImage)
attrMub.append(attrStr2)
//然后把可变富文本对象赋值给UILabel的相应的属性
demoLabel.attributedText = attrMub
至此简单的图文混排就完成了
网友评论