iOS 图文混排
2020-04-23 本文已影响0人
LionPig
- 创建label
let label = UILabel(frame:CGRect(origin: .zero, size:CGSize(width:265, height:40)))
label.numberOfLines = 0
- 创建富文本
let attStr = NSMutableAttributedString(string: "xxxx")
- 创建图片文本
let textAttach = NSTextAttachment()
- 富文本添加图片
textAttach.image = UIImage(named:"lottery_alert_warning")
textAttach.bounds = CGRect(origin: .zero, size:CGSize(width:14, height:14))
- 图片和文字居中对齐
let font = UIFont.systemFont(ofSize:14)
let paddingTop = font.lineHeight-font.pointSize
textAttach.bounds = CGRect(x:0, y: -paddingTop, width: font.lineHeight, height: font.lineHeight)
- 图片文本加入富文本中
let imageAtt = NSAttributedString(attachment: textAttach)
- 图片插入文本中位置
attStr.insert(imageAtt, at:0)
- 一些其他设置
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2
paragraphStyle.alignment = .justified
let attrkey = [NSAttributedString.Key.font:font,
NSAttributedString.Key.foregroundColor:UIColor(hex:"333333"),
NSAttributedString.Key.paragraphStyle:paragraphStyle]
attStr.addAttributes(attrkey, range:NSRange(location:0, length: attStr.string.count))
- 富文本赋值给label
label.attributedText = attStr