最近在开发中,遇到一个奇怪的问题,就是当显示一串文本,当文本最后一个字符是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))