Ios 使用NSMutableParagraphStyle会导致emojis出现问题

Ios 使用NSMutableParagraphStyle会导致emojis出现问题,ios,swift,string,Ios,Swift,String,在我的应用程序中,我想更改线条高度,我使用以下字符串扩展名: extension String { func addLineHeightWith(alignement: NSTextAlignment) -> NSAttributedString { let attrString = NSMutableAttributedString(string: self) let style = NSMutableParagraphStyle()

在我的应用程序中,我想更改线条高度,我使用以下字符串扩展名:

extension String {
    func addLineHeightWith(alignement: NSTextAlignment) -> NSAttributedString {
        let attrString = NSMutableAttributedString(string: self)
        let style = NSMutableParagraphStyle()
        style.lineSpacing = 5
        style.minimumLineHeight = 5
        style.alignment = alignement
        attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: self.count))
        return attrString
    }
}
我正在尝试将其应用于UILabel:

let str = "Hi%5E%5E%F0%9F%98%AC%F0%9F%98%AC%F0%9F%98%AC%F0%9F%98%AC%F0%9F%98%AC%F0%9F%98%AC%F0%9F%98%AC"

if let decoded = str.removingPercentEncoding {
     print(decoded)
     label.attributedText = decoded.addLineHeightWith(alignement: .center)
}
以下是控制台中的结果:

屏幕上的结果是:


有什么想法吗?谢谢

问题在于您使用的是
NSRange(位置:0,长度:self.count)

self.count
是Swift
字符串中正确的字符数。但是
NSAttributedString
基于
NSString
及其UTF-16编码字符的使用。您最终只将样式应用于实际字符串的大约一半。事实上,它将其中一个角色一分为二

简单的解决方法是将字符串的长度作为
NSString
获取

替换:

NSRange(location: 0, length: self.count)
与:


那太好了。谢谢你,祝你今天愉快
NSRange(location: 0, length: (self as NSString).length))