Swift UIlabel 的高级用法,文本显示表情,图片
2018-04-05 本文已影响160人
_东阁堂主_
可以定义一个UIlabel的扩展代码如下
class CPSPFMarkLabel: UILabel {
convenience init(text: String) {
self.init(frame:CGRect.zero)
let markLabelText = " 清明时节雨纷纷☺" + text
self.textAlignment = .center
self.textColor = UIConstants.AppFontColor
self.font = UIConstants.DefaultFont15
self.backgroundColor = UIConstants.AppWhiteColor
let markAttribute = NSMutableAttributedString(string: markLabelText)
markAttribute.addAttribute(NSAttributedStringKey.foregroundColor, value:UIConstants.AppRedColor, range: NSRange(location: 6,length: text.count))
//以上是富文本显示
let arkattch = NSTextAttachment() //定义一个attachment
markattch.image = UIImage(named: "image_timing")//初始化图片
markattch.bounds = CGRect(x: 0, y: -1, width: 15, height: 15) //初始化图片的 bounds
let markattchStr = NSAttributedString(attachment: markattch) // 将attachment 加入富文本中
markAttribute.insert(markattchStr, at: 0)// 将markattchStr 加入原有文字的某个位置
self.attributedText = markAttribute
}
}
image