Emoji loss when using NSMutableAttributedString on UILabel Emoji loss when using NSMutableAttributedString on UILabel swift swift

Emoji loss when using NSMutableAttributedString on UILabel


Your problem is with your NSRange calculations when setting the attributes. NS[Mutable]AttributeString needs the NSRange to be based on NSString ranges, not String ranges.

So code like:

NSRange.init(location: 0, length: commentString.count)

Needs to be written as either:

NSRange(location: 0, length: (commentString as NSString).length)

or:

NSRange(location: 0, length: commentString.utf16.count)

The following demonstrates the issue with commentString.count:

let comment = "💃👍👍"print(comment.count) // 3print((comment as NSString).length) // 6print(comment.utf16.count) // 6

This is why your code seems to be splitting the middle character in half. You are passing in half (in this case) the needed length.


Proper way to do this in Swift 4 is using indexes on String:

NSRange(location: 0, length: commentString.endIndex.encodedOffset)