乐趣区

Swift UIlabel 的高级用法,文本显示表情,图片

可以定义一个 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
}
}

退出移动版