IOS开发微博富文本处理及替换表情

时间:2024-03-07 11:15:27
//
//  TTWeiboMiddleware.swift
//  TinyTimes
//
//  Created by Alex on 16/3/21.
//  Copyright © 2016年 Alex. All rights reserved.
//

import UIKit
//以前写的代码有缺陷这个对于weibocell的补充
class TTWeiboMiddleware: UITableViewCell {
    static var regex:NSRegularExpression?
    func emojiAttributedString(string:String,font:UIFont)->NSAttributedString{
        let parsedOutput = NSMutableAttributedString(string: string, attributes: [NSFontAttributeName:font]);
        let originalString = String(string);
        let originalNSString  = NSString(string: string);
//        var regex:NSRegularExpression? = nil ;
        do{
            if getRegex() == nil{
                TTWeiboMiddleware.regex = try NSRegularExpression(pattern: "\\[[\\u4e00-\\u9fa5|a-z|A-Z]+\\]", options: NSRegularExpressionOptions.CaseInsensitive);
            }
        }catch let err as NSError{
            print (err);
            return parsedOutput;
        }
        if let regex = getRegex(){
            if let emoji = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("emotionImage", ofType: "plist")!){
                let matches = regex.matchesInString(originalString, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0,parsedOutput.string.characters.count));
                let size = CGSizeMake(font.lineHeight,font.lineHeight);
                if matches.count>0{

                    for  var i = matches.count - 1;i>=0;i-- {
                        let result = matches[i];
                        let range = result.range;
                        let placeholder = originalNSString.substringWithRange(range);
                        //如果本地有对应的表情则解析
                        if let emojiName = emoji.objectForKey(placeholder) as? String{
                                if let image = UIImage(named: emojiName){
                                    UIGraphicsBeginImageContext(size);
                                    image.drawInRect(CGRectMake(0,0,size.width,size.height));
                                    let sizedImage = UIGraphicsGetImageFromCurrentImageContext();
                                    UIGraphicsEndImageContext();
                                    let attachment = NSTextAttachment();
                                    attachment.image = sizedImage;
                                    let rep = NSAttributedString(attachment: attachment);
                                    parsedOutput.replaceCharactersInRange(range, withAttributedString: rep);
                                }
                        }
                    }
                        
                }

            }
        
        }
        return parsedOutput;
    }
    func getRegex()->NSRegularExpression?{
        return TTWeiboMiddleware.regex;
    }
}

 

 let matches = regex.matchesInString(originalString, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0,parsedOutput.string.characters.count));



获取String的长度,一定要用.characters.count 这样一个英文字符长度是1,一个中文汉字长度也是1 得到的正则表达式对象,应该从后往前替换. 从前往后替换时候会改变字符串长度,导致匹配到的range与原来不一致 PS 感觉swift里面的正则表达式好难用..

效果图:

里面没有替换的是本地没有...