美文网首页
包含image的富文本转化为String

包含image的富文本转化为String

作者: 悃破 | 来源:发表于2017-10-31 16:19 被阅读130次

    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

    相关文章

      网友评论

          本文标题:包含image的富文本转化为String

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