美文网首页
swift 图文混排 表情的插入

swift 图文混排 表情的插入

作者: 陈水寒 | 来源:发表于2017-11-13 11:58 被阅读74次

给textView写一个扩展,增加2个方法,一个是获取图文混排后的string,一个是往textView里插入表情

    func getEmoticonString() -> String {
        // 截取字符串
        let attMStr = NSMutableAttributedString(attributedString: attributedText)
        
        let range = NSRange.init(location: 0, length: attMStr.length)
        attMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            if  let attachment = dict["NSAttachment"] as? GGEmoticonAttachment {
                attMStr.replaceCharacters(in: range, with: attachment.chs!)
            }
        }
        
        return attMStr.string
    }
    
    /// 插入表情
    ///
    /// - Parameter emoticon: 需要插入的表情
    func insertEmoticon(emoticon : GGEmoticon) {
        // 1.空白表情
        if emoticon.isEmpty {
            return
        }
        
        // 2.删除表情
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        
        // 3.emoji表情
        if emoticon.emojiCode != nil {
            let textRange = selectedTextRange!
            // 插入表情
            replace(textRange, withText: emoticon.emojiCode!)
            return
        }
        
        // 4.图文混排
        let textAtt = GGEmoticonAttachment()
        textAtt.chs = emoticon.chs
        textAtt.image = UIImage.init(contentsOfFile: emoticon.pngPath!)
        let font = self.font!
        textAtt.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
        let attStr = NSAttributedString(attachment: textAtt)
        
        let attMutalbeStr = NSMutableAttributedString(attributedString: attributedText)
        let range = selectedRange
        attMutalbeStr.replaceCharacters(in: range, with: attStr)
        
        attributedText = attMutalbeStr
        
        self.font = font
        
        // 将光标返回原来的位置
        selectedRange = NSRange.init(location: range.location + 1, length: 0)
    }

相关文章

网友评论

      本文标题:swift 图文混排 表情的插入

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