我正在尝试实现来自 Sketch 的按设计标签,例如我需要字体大小 = 19 和行高 = 50 的文本样式。所以我最终使用NSAttributedString
with NSMutableParagraphStyle
但因文本粘在底部的问题而停止UILabel
我已经尝试过使用lineHeightMultiple
and lineSpacing
但这些并没有给我想要的行高,所以我最终使用了minimumLineHeight
and maximumLineHeight
等于相同
这是我的方法NSAttributedString
private static func makeAttributedString(
with attributes: TextAttributes,
text: String? = nil,
alignment: NSTextAlignment = .center
) -> NSAttributedString {
let font = UIFont(name: attributes.font.rawValue, size: attributes.fontSize)!
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = alignment
paragraph.paragraphSpacing = attributes.paragraph
paragraph.minimumLineHeight = attributes.lineHeight // equal 50 in my case
paragraph.maximumLineHeight = attributes.lineHeight // equal 50 in my case
let attributes: [NSAttributedStringKey: Any] = [
NSAttributedStringKey.paragraphStyle: paragraph,
NSAttributedStringKey.foregroundColor: attributes.textColor,
NSAttributedStringKey.kern: attributes.kern,
NSAttributedStringKey.font: font
]
return NSAttributedString(string: text ?? "", attributes: attributes)
}
我期望结果与设计类似
但实际上得到
注意:将高度限制设置为 50 不适用,因为我还需要多行标签,但它们存在相同的错误
看来我自己找到了一些解决方法,也许会对某人有所帮助。
该方法是关于设置baselineOffset,如下所示:
NSAttributedStringKey.baselineOffset: (attributes.lineHeight - font.lineHeight) / 4
像魅力一样工作:
https://i.stack.imgur.com/KS6k0.png https://i.stack.imgur.com/KS6k0.png
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)