gpt4 book ai didi

ios - 使用 NSMutableParagraphStyle 会导致表情符号出现问题

转载 作者:行者123 更新时间:2023-11-28 07:48:19 24 4
gpt4 key购买 nike

在我的应用程序中,我想更改行高,我正在使用这个字符串扩展:

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)
}

这是控制台的结果:

enter image description here

屏幕上的结果:

enter image description here

有什么想法吗?谢谢

最佳答案

问题出在您对 NSRange(location: 0, length: self.count) 的使用上。

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

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

替换:

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

与:

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

关于ios - 使用 NSMutableParagraphStyle 会导致表情符号出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50338316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com