给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)
}
网友评论