最近在開發(fā)中,遇到一個奇怪的問題,就是當(dāng)顯示一串文本,當(dāng)文本最后一個字符是Emoji時,Emoji顯示亂碼,如圖:

錯誤展示
正確展示應(yīng)該是這樣的

正確展示
而展示邏輯也很簡單,一個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
當(dāng)用Swift.count計算長度時出錯,修復(fù)也很簡單,
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: (introduction as NSString).length))