iOS Add spacing to line of text - Swift

This week while working on one of our internal apps (Again), I came across an interesting problem to add spacing to line labels. I never knew iOS could do it. My first and very naive solution was to have multiple UILabels and arrange them vertically. But this would cause a problem since UILabel may or may not be able to accommodate single line of text and expand to next line which may distort the whole scene.

Fortunately, thanks to the power of Google, I was able to do it real quick.

Since everyone is using Swift nowadays, I will provide an example in Swift as well. Following example demonstrates the implementation of custom line spacing in swift. The function updateWithSpacing takes line spacing as an input parameters which is of type Float. This value comes directly from the UISlider which user can slide to change the line spacing on the fly.


func updateWithSpacing(lineSpacing: Float) {
    // The attributed string to which the 
    // paragraph line spacing style will be applied.
    let attributedString = NSMutableAttributedString(string: textLabel.text!)
    let mutableParagraphStyle = NSMutableParagraphStyle()
    // Customize the line spacing for paragraph.
    mutableParagraphStyle.lineSpacing = CGFloat(lineSpacing)

    if let stringLength = textLabel.text?.characters.count {
                attributedString.addAttribute(NSParagraphStyleAttributeName, value: mutableParagraphStyle, range: NSMakeRange(0, stringLength))
    }
    // textLabel is the UILabel subclass 
    // which shows the custom text on the screen
    textLabel.attributedText = attributedString
    // currentValueLabel is the label which displays 
    // the  current value of UISlider (Which in turn is the line spacing). 
    // This can be changed on the fly by sliding the UISlider.
    currentValueLabel.text = String(format: "%.1f", lineSpacing)
}

Here are the screenshots of how the label looks like for different values of line spacing.


small


medium


large


This is how it looks like when animated using UISlider

custom_line_spacing_demo

The source code for this project is available on the GitHub. Feel free to comment, criticize and give your valuable feedback

It would also be sweet if you are willing to improve the code and make a pull request. In the meantime feel free to reach out to me if you have any further questions