iOS - Swift - NSAttributedString 显示Emoji乱码问题

最近在开发中,遇到一个奇怪的问题,就是当显示一串文本,当文本最后一个字符是Emoji时,Emoji显示乱码,如图:


错误展示

正确展示应该是这样的


正确展示

而展示逻辑也很简单,一个UILabel控件通过attributedText展示

signLabel.attributedText = user.introductionAttribute

如果用label.text展示的话,则是正常的

signLabel.text= user.introduction

直接说问题点和解决方案:

    var introductionAttribute: NSAttributedString {
        let attributedString = NSMutableAttributedString(string: introduction,
                                                         attributes: [.font: YRUserHeaderLayoutable.introFont])
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.paragraphSpacing = 0
        paragraphStyle.firstLineHeadIndent = 0
        paragraphStyle.headIndent = 0
        paragraphStyle.paragraphSpacingBefore = 0
        attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: introduction.count))
        return attributedString
    }

问题出在了最后一行代码

 attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: introduction.count))

在计算字符串长度时, Swift计算的是

/// The number of characters in a string.
 public var count: Int { get }
let swiftCount = introduction.count
let ocLength = (introduction as NSString).length
print("introducetion:\(introduction)")
print("swiftCount:\(swiftCount)")
print("ocLength:\(ocLength)")

打印:

introducetion:这是一个emoji😁
swiftCount:10
ocLength:11

当用Swift.count计算长度时出错,修复也很简单,

attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: (introduction as NSString).length))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 11,278评论 0 4
  • 公元:2019年11月28日19时42分农历:二零一九年 十一月 初三日 戌时干支:己亥乙亥己巳甲戌当月节气:立冬...
    石放阅读 11,804评论 0 2
  • 今天上午陪老妈看病,下午健身房跑步,晚上想想今天还没有断舍离,马上做,衣架和旁边的的布衣架,一看乱乱,又想想自己是...
    影子3623253阅读 7,962评论 3 8