hh3*_*7a1 5 nsattributedstring uilabel ios swift
我正在尝试实现来自 Sketch 的按设计标签,例如我需要字体大小 = 19 且行高 = 50 的文本样式。所以我最终使用了NSAttributedStringwith NSMutableParagraphStyle,但由于文本粘在底部的问题而停止了UILabel
我已经尝试使用lineHeightMultipleandlineSpacing但那些并没有给我我想要的行高,所以我最终使用minimumLineHeightandmaximumLineHeight等于相同
这是我的方法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)
}
Run Code Online (Sandbox Code Playgroud)
我期望结果与设计类似

但实际上得到

注意:将高度限制设置为 50 不适用,因为我还需要多行标签,但它们存在相同的错误
看来我自己找到了一些解决方法,也许会对某人有所帮助。
该方法是关于设置baselineOffset,如下所示:
NSAttributedStringKey.baselineOffset: (attributes.lineHeight - font.lineHeight) / 4
Run Code Online (Sandbox Code Playgroud)
像魅力一样工作:
https://i.stack.imgur.com/KS6k0.png
| 归档时间: |
|
| 查看次数: |
1567 次 |
| 最近记录: |