使用NSMutableParagraphStyle会导致emojis出现问题
在我的应用程序中,我想更改行高,我正在使用此字符串扩展名:
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(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))