如何为UILabel设置字符(字距)和删除线样式之间的间距? [英] How to set both spacing between characters (kern) and strikethrough style for `UILabel`?

查看:61
本文介绍了如何为UILabel设置字符(字距)和删除线样式之间的间距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为由 UILabel 呈现的文本设置两个属性:字母之间的间距(kern)及其删除线样式.基于 NSAttributedStringKey 文档,我为 UILabel 创建了以下扩展名:

I need to set two attributes to a text presented by a UILabel: spacing between letters (kern), and its strikethrough style. Based on the NSAttributedStringKey documentation I have created the following extension to the 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 属性),则删除线样式有效.

However, it seems that .kern key somehow collides with the .strikethroughStyle key, because if I specify kern, the kern is applied, but not the strikethrough style. If I don't specify kern (so the extension does not apply the .kern attribute), the strikethrough style works.

每个人都有不同的方法来解决此错误(我认为这是一个错误)吗?

Anyone has a different way how to work around this bug (I assume this is a bug)?

推荐答案

尝试一下,它应该对您有用
注意:我在 Swift 4

Try this, it should work for you
Note: I tested in 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


结果:
模拟1:打击+ LineSpacing
模拟2:罢工+行距+字符间距


Result:
Sim 1: Strike + LineSpacing
Sim 2: Strike + LineSpacing + Character Spacing

这篇关于如何为UILabel设置字符(字距)和删除线样式之间的间距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆