如何解决使用基线偏移量将NSAttributedString垂直设置在每行中心
我想设置标签的行高,并使用minimumLineHeight
中的maximumLineHeight
和NSMutableParagraphStyle
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
属性,因为没有它,文本就这样粘在底部。
我想要的是垂直设置文本中心,因此使用baselineOffset解决了该问题。但是我不知道为什么将baseOffline设置为(attributes.lineHeight - font.lineHeight) / 4
而不是(attributes.lineHeight - font.lineHeight) / 2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。