使用基线偏移量将NSAttributedString垂直设置在每行中心

问题描述

我想设置标签的行高,并使用minimumLineHeight中的maximumLineHeightNSMutableParagraphStyle

extension UILabel {
    func setTextWithLineHeight(text: String?,lineHeight: CGFloat) {
        if let text = text {
            let style = NSMutableParagraphStyle()
            style.maximumLineHeight = lineHeight
            style.minimumLineHeight = lineHeight
            
            let attributes: [NSAttributedString.Key: Any] = [
                .paragraphStyle: style
                .baselineOffset: (lineHeight - font.lineHeight) / 4 // added!!️️?
            ]
                
            let attrString = NSAttributedString(string: text,attributes: attributes)
            self.attributedText = attrString
        }
    }
}

我根据答案NSAttributedString text always sticks to bottom with big lineHeight添加.baselineOffset属性,因为没有它,文本就这样粘在底部

image

我想要的是垂直设置文本中心,因此使用baselineOffset解决了该问题。但是我不知道为什么将baSEOffline设置为(attributes.lineHeight - font.lineHeight) / 4而不是(attributes.lineHeight - font.lineHeight) / 2

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)