4

I want to set label's line height and I use minimumLineHeight and maximumLineHeight of 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
        }
    }
}

I add .baselineOffset attribute based on a answer NSAttributedString text always sticks to bottom with big lineHeight , because without it, text is sticks to bottom like this.

image

What I want is set text center vertically so using baselineOffset, I solved the problem. However I wonder why it set baseOffline as (attributes.lineHeight - font.lineHeight) / 4 not (attributes.lineHeight - font.lineHeight) / 2

Willeke
  • 14,578
  • 4
  • 19
  • 47
naljin
  • 439
  • 3
  • 10
  • 1
    Happens the same with me as well. Be aware, however, that there are some scenarios when the offset works as expected. There some more details in the article I'm writing on `UILabel` line height at http://blog.eppz.eu/uilabel-line-height-letter-spacing-and-more-uilabel-typography-extensions/, may or may not help. Also, see https://developer.apple.com/forums/thread/124799 if any updates there. – Geri Borbás Jan 04 '21 at 05:11

0 Answers0