如何为`UILabel`设置字符间的间距(kern)和删除线样式?
我需要将两个属性设置为由UILabel
表示的文本:字母间的间距(kern)及其删除线样式。基于该NSAttributedStringKey
文件我已经创建了以下扩展到UILabel
:如何为`UILabel`设置字符间的间距(kern)和删除线样式?
extension UILabel {
func setStrikeThroughSpacedText(text: String, kern: CGFloat?) {
var attributes: [NSAttributedStringKey : Any] = [:]
if let kern = kern {
attributes[.kern] = kern
}
attributes[.strikethroughStyle]
= NSNumber(integerLiteral: NSUnderlineStyle.styleSingle.rawValue)
self.attributedText = NSAttributedString(string: text,
attributes: attributes)
}
}
然而,似乎.kern
关键不知何故与.strikethroughStyle
键冲突,因为如果我指定克恩应用克恩,而不是删除线样式。如果我没有指定kern(所以扩展名不适用.kern
属性),则删除线样式起作用。
任何人有不同的方式如何解决这个错误(我认为这是一个错误)?
试试这个,它应该为你
注意工作:我在测试雨燕4
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
let style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.count))
attrString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attrString.length))
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
结果:
星际1:攻击+ LineSpacing
星际2:罢工+ LineSpacing +字符间距
'.kern'属性设置字符间距,而不是行距 –
它适用于iOS 11,但不适用于iOS 10 ..这就是问题所在。 –
尝试使用Xcode 9(Swift 4)和iOS 10模拟器。 (你可能会使用Xcode 8和Swift 3) – Krunal
这确实看起来像一个错误。你提交了雷达吗? – the4kman
还没有..虽然我只是在iOS 11上的模拟器中测试它,它似乎在那里工作..所以它似乎在那里修复它.. –
查看更新的答案和结果。 – Krunal