使用NSMutableParagraphStyle导致表情符号出现问题 [英] Using NSMutableParagraphStyle cause issue with emojis

查看:55
本文介绍了使用NSMutableParagraphStyle导致表情符号出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我想更改行高,我正在使用此字符串扩展名:

In my app I want to change the line height, I am using this string extension :

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:

I am trying to apply it in a 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 String 中正确的字符数.但是 NSAttributedString 是基于 NSString 及其使用UTF-16编码字符的.您最终只能将样式应用于实际字符串的大约一半.实际上,它会将其中一个字符分成两半.

self.count is the proper number of characters in the Swift String. But the NSAttributedString is based on NSString and its use of UTF-16 encoded characters. You end up applying the style to only about half of the actual string. In fact, it splits one of the characters in half.

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

The easy fix is to get the length of the string as an NSString.

替换:

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

具有:

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

这篇关于使用NSMutableParagraphStyle导致表情符号出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆