//使用string 创建 NSMutableString
var msgtext : NSMutableString = NSMutableString(string: msg.text)
var range :NSRange = NSRange()
var emoji : String = ""
var locationlist : NSMutableArray = NSMutableArray()
var location : NSDictionary = NSDictionary()
//获取表情的位置信息和表情的具体信息带[emoji_ 及其后3位
while msgtext.rangeOfString("[emoji_").location != NSNotFound {
range = msgtext.rangeOfString("[emoji_")
if msgtext.length > (range.location + range.length + 2){
range = NSRange(location: range.location,length: range.length+3)
emoji = msgtext.substringWithRange(range)
//str.replaceCharactersInRange(aaa, withString: "")
msgtext.replaceCharactersInRange(range, withString: "")
location = ["loc" : range , "emoji" : emoji]
locationlist.addObject(location)
}else{
break
}
}
var string:NSMutableAttributedString = NSMutableAttributedString(string: msgtext as String, attributes: nil)
//从后面向前依次替换表情,(从前向后的时候位置信息出现错误),10以内的补0
for local in locationlist.reverseObjectEnumerator(){
var emojilist:[String] = (local["emoji"] as! String).componentsSeparatedByString("_")
let emojinum = emojilist[1]._bridgeToObjectiveC().integerValue
println(emojinum)
var range :NSRange = local["loc"] as! NSRange
if emojinum >= 10{
var textAttachment:NSTextAttachment = NSTextAttachment(data: nil, ofType: nil)
var smileImage:UIImage = UIImage(named: "xiaoming")!
var picname : String = "emoji_\(emojinum)"
smileImage = UIImage(named: picname)!
textAttachment.image = smileImage
var textAttachmentString:NSAttributedString = NSAttributedString(attachment: textAttachment)
//var range :NSRange = local["loc"] as! NSRange
string.insertAttributedString(textAttachmentString, atIndex: range.location)
}else if emojinum > 0{
var textAttachment:NSTextAttachment = NSTextAttachment(data: nil, ofType: nil)
var smileImage:UIImage = UIImage(named: "xiaoming")!
var picname : String = "emoji_0\(emojinum)"
smileImage = UIImage(named: picname)!
textAttachment.image = smileImage
var textAttachmentString:NSAttributedString = NSAttributedString(attachment: textAttachment)
string.insertAttributedString(textAttachmentString, atIndex: range.location)
}else{
var textAttachmentString:NSAttributedString = NSAttributedString(string: local["emoji"] as! String)
string.insertAttributedString(textAttachmentString, atIndex: range.location)
}
}
可以替换的表情格式为[emoji_01],,这样的。
最后使用
messageContentView.attributedText = string
将string放入一个textview中