美文网首页
iOS 图文混排

iOS 图文混排

作者: LionPig | 来源:发表于2020-04-23 21:57 被阅读0次
  • 创建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

相关文章

网友评论

      本文标题:iOS 图文混排

      本文链接:https://www.haomeiwen.com/subject/qigzihtx.html