NSAttributedString 文本总是以大 lineHeight 贴在底部 [英] NSAttributedString text always sticks to bottom with big lineHeight

查看:31
本文介绍了NSAttributedString 文本总是以大 lineHeight 贴在底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现来自 Sketch 的设计标签,例如我需要字体大小 = 19 和行高 = 50 的文本样式.所以我最终将 NSAttributedStringNSMutableParagraphStyle 一起使用,但由于文本被粘贴到 <底部的问题而停止了代码>UILabel

I'm trying to implement by-design labels coming from Sketch e.g. I need text styles with font size = 19 and line height = 50. So I ended up using NSAttributedString with NSMutableParagraphStyle but was stopped by problem with text being sticked to bottom of UILabel

我已经尝试使用 lineHeightMultiplelineSpacing 但它们没有给我想要的行高,所以我最终使用了 minimumLineHeightmaximumLineHeight 相等

I've already tried to use lineHeightMultiple and lineSpacing but those didn't give me the line height I wanted so I ended up using minimumLineHeight and maximumLineHeight equal the same

这是我制作 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 不适用,因为我也需要多行标签,但它们存在相同的错误

Note: setting height constraint to 50 is not applicable because I also need multiline labels but there is the same bug with them

推荐答案

似乎我自己找到了一些解决方法,也许会对某人有所帮助.

Seems like I've found some workaround myself, maybe it will help someone.

该方法是关于像这样设置baselineOffset:

The method is about setting baselineOffset like this:

NSAttributedStringKey.baselineOffset: (attributes.lineHeight - font.lineHeight) / 4

像魅力一样工作:

https://i.imgur.com/a2EOf5R.png

这篇关于NSAttributedString 文本总是以大 lineHeight 贴在底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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