1、String转化为富文本(带图片)
//给NSTextAttachment添加一个属性,用于标记富文本转化为String是图片需要转化的文字
class EmojiTextAttachment: NSTextAttachment {
var emojiTag: String?
}
//生成一个富文本
func makeAttributeString() -> NSAttributedString {
let str = "生成一个富文本,后面随意加一张图片"
var attrStr = NSMutableAttributedString(string: str)
let attachment = EmojiTextAttachment()
attachment.emojiTag = "这里是图片转化成的文字"
attachment.image = UIImage(named: "插入的图片")
// attachment.bounds = CGRect() //插入图片的大小
let att = NSAttributedString(attachment: attachment)
attrStr.append(att) //直接添加到末尾
// attrStr.insert(att, at: 3)// 插入
}
2、富文本转化为String
extension NSAttributedString {
func plainString() -> String {
var targetString: NSMutableString = NSMutableString(string: self.string)
//替换下标的偏移量
var base = 0
//遍历
self.enumerateAttribute(NSAttachmentAttributeName, in: NSRange(location: 0, length: self.length), options: .init(rawValue: 0)) { (value, range, stop) in
//检查类型是否是自定义NSTextAttachment类
if let attach = value as? EmojiTextAttachment {
//替换
targetString.replaceCharacters(in: NSRange(location: range.location + base, length: range.length), with: attach.emojiTag!)
//增加偏移量
base = base + (attach.emojiTag?.count)! - 1
}
}
return targetString as String
}
}
如有错误欢迎指正
方便搜索:
NSAttributedString与String互转
NSAttributedString转String
网友评论