iOS開發進階 - 富文本正則替換表情

MarUmberger 8年前發布 | 11K 次閱讀 iOS開發 正則表達式 移動開發

最近寫項目需要用到富文本解析字符串顯示表情,下面是我使用正則替換實現富文本的方式,希望能幫助到大家

先上效果圖

實現過程中需要用到的知識點

  • NSRegularExpression(正則表達式)
  • NSMutableAttributedString(用來顯示富文本的string)

廢話不多說,直接貼代碼:

import UIKit

struct WCLEmojiParse {

    //所有表情對應的字符串
    static let emotions = ["[angry]", "[beers]", "[blush]", "[bomb]", "[cool]", "[flushed]", "[grin]", "[gun]", "[heart]", "[heartseyes]", "[imp]", "[Joy]", "[kiss]", "[ok]", "[persevere]", "[pray]", "[punch]", "[scream]", "[shit]", "[skull]", "[sleeping]", "[smiley]", "[smirk]", "[sob]","[sweat]", "[thumbsup]", "[tongue]", "[unamused]", "[v]", "[weary]", "[wink]", "[yum]"]

    //String的格式
    static let textAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor.black]
    //正則表達式的格式
    static let pattern = "\\[+[a-z]+\\]"
    //表情的bounds
    static let attachmentBounds = CGRect.init(origin: CGPoint.init(x: 0, y: -5), size: CGSize.init(width: 24, height: 24))

    //MARK: Public Methods
    static func replaceEmoji(_ str: String) -> NSAttributedString {
        //轉成NSString
        let originalNSString = str as NSString
        //通過str獲得NSMutableAttributedString
        let attStr = NSMutableAttributedString.init(string: str, attributes: textAttributes)
        var regex: NSRegularExpression?
        do {
            regex = try NSRegularExpression.init(pattern: pattern, options: .caseInsensitive)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        //獲取到匹配正則的數據
        if let matches = regex?.matches(in: str, options: .withoutAnchoringBounds, range: NSMakeRange(0,attStr.string.characters.count)) {
            if matches.count > 0 {
                //遍歷符合的數據進行解析
                for i in 0..<matches.count {
                    let result = matches[matches.count-i-1]
                    let range = result.range
                    let emojiStr = originalNSString.substring(with: range)
                    //符合的數據是否為表情
                    if emotions.contains(emojiStr) {
                        if let image = UIImage.init(named: emojiStr) {
                            //創建一個NSTextAttachment
                            let attachment    = NSTextAttachment()
                            attachment.image  = image
                            attachment.bounds = attachmentBounds
                            //通過NSTextAttachment生成一個NSAttributedString
                            let rep = NSAttributedString(attachment: attachment)
                            //把表情于之前的字符串替換
                            attStr.replaceCharacters(in: range, with: rep)
                        }
                    }
                }
            }
        }
        return attStr
    }
}

以上是簡單的富文本顯示表情的方式,拋磚引玉,大家見笑了,希望大家能學到東西。

 

 

來自:http://imwcl.com/2016/11/28/iOS開發進階-富文本正則替換表情/

 

 本文由用戶 MarUmberger 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!