iOS开发进阶 - 富文本正则替换表情

MarUmberger 8年前
   <p>最近写项目需要用到富文本解析字符串显示表情,下面是我使用正则替换实现富文本的方式,希望能帮助到大家</p>    <p>先上效果图</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/6148674172fade434b467c0b373c0290.jpg"></p>    <p>实现过程中需要用到的知识点</p>    <ul>     <li>NSRegularExpression(正则表达式)</li>     <li>NSMutableAttributedString(用来显示富文本的string)</li>    </ul>    <p>废话不多说,直接贴代码:</p>    <pre>  <code class="language-objectivec">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      }  }  </code></pre>    <p>以上是简单的富文本显示表情的方式,抛砖引玉,大家见笑了,希望大家能学到东西。</p>    <p> </p>    <p> </p>    <p>来自:http://imwcl.com/2016/11/28/iOS开发进阶-富文本正则替换表情/</p>    <p> </p>