在我的应用程序中,我想更改行高,我使用此字符串扩展名:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我想在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)
}
Run Code Online (Sandbox Code Playgroud)
这是控制台中的结果:
并在屏幕上显示结果:
任何的想法?谢谢
问题在于您的使用NSRange(location: 0, length: self.count).
self.count是Swift中正确的字符数String.但它NSAttributedString是基于NSString和使用UTF-16编码的字符.您最终将样式应用于实际字符串的大约一半.事实上,它将其中一个角色分成两半.
简单的解决方法是将字符串的长度作为一个NSString.
更换:
NSRange(location: 0, length: self.count)
Run Code Online (Sandbox Code Playgroud)
有:
NSRange(location: 0, length: (self as NSString).length))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |