UILabel line height in Swift

Often while developing iOS Apps, it can occur to have to implement Design parts which include text paragraphs. Frequently it can happen that the custom LineHeight is not the one desired.


Luca D'Incร 

16 Sep 2015


Line height

LineHeight, as shown in the image, is the height of a single text line including the font size too.

UILabel + LineHeight

Unfortunately, iOS native APIs wonโ€™t make anything available to the developer to set up the LineHeight within a UILabel. Apple offers two very powerful classes to solve this issue, which are NSMutableAttributedString and NSMutableParagraphStyle

As specified by Apple records:

The NSMutableParagraphStyle class adds methods to its superclass, NSParagraphStyle, for changing the values of the subattributes in a paragraph style attribute. See the NSParagraphStyle and NSAttributedString specifications for more information.

NSMutableParagraphStyle provides lineSpacing, which will be our solution.

LineSpacing allows the developer to apply a desired lineHeight to a text line.

I created an UILabel extension implementing a specific feature, setLineHeight(lineHeight: CGFloat), to complement this feature inside a UILabel.

This is the code fragment to implement within your projects:

import UIKit
extension UILabel {
    func setLineHeight(lineHeight: CGFloat) {
        let text = self.text
        if let text = text {
            let attributeString = NSMutableAttributedString(string: text)
            let style = NSMutableParagraphStyle()
            style.lineSpacing = lineHeight
            attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, count(text)))
            self.attributedText = attributeString


Luca D'Incร