在我的应用程序中,我想更改行高,我使用这个字符串扩展名:
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)
}以下是控制台的结果:

屏幕上的结果是:

有什么想法吗?谢谢
发布于 2018-05-10 05:52:28
问题在于您如何使用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))https://stackoverflow.com/questions/50266204
复制相似问题