NSAttributedString text always sticks to bottom with big lineHeight

混江龙づ霸主 提交于 2020-12-13 03:28:56

问题


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

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

Here is my approach to make 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)
    }

I expect result similar to design

but actually getting

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


回答1:


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

The method is about setting baselineOffset like this:

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

Works like charm:

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



来源:https://stackoverflow.com/questions/56973156/nsattributedstring-text-always-sticks-to-bottom-with-big-lineheight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!