天天看点

NSMutableAttributeString中,由于表情导致string count 计算不准确问题

正确用法:attrStr.addAttribute(.foregroundColor, value: JFColors.title, range: NSRange(location: 0, length: replyModel.content.utf16.count))

NSMutableAttributeString,在添加attribute时,Range计算使用str.count,当string中有表情时,count计算不准确,导致异常。

解决办法:使用string.utf16.count计算string长度。

在Swift官方文档中,关于String的介绍中有这么一句话:

NSMutableAttributeString中,由于表情导致string count 计算不准确问题

它说明在NSString相关计算中,使用的是UTF-16。