gpt4 book ai didi

ios - 如何为 `UILabel` 设置字符间距 (kern) 和删除线样式?

转载 作者:搜寻专家 更新时间:2023-10-30 22:31:50 60 4
gpt4 key购买 nike

我需要为 UILabel 显示的文本设置两个属性:字母间距 (kern) 及其删除线样式。根据 NSAttributedStringKey 文档,我为 UILabel 创建了以下扩展:

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,但不会应用删除线样式。如果我不指定 kern(因此扩展不应用 .kern 属性),则删除线样式有效。

谁有不同的方法来解决这个错误(我认为这是一个错误)?

最佳答案

试试这个,它应该适合你
注意:我在Swift 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


结果:
Sim 1: Strike + LineSpacing
Sim 2:Strike + LineSpacing + Character Spacing

enter image description here

关于ios - 如何为 `UILabel` 设置字符间距 (kern) 和删除线样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46172079/

60 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com