在我的应用程序中,我想更改行高,我正在使用此字符串扩展名:
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)
}
以下是控制台中的结果:
屏幕上的结果:
有什么想法吗?谢谢
答案 0 :(得分:7)
问题在于您使用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))