Adding NSMutableParagraphStyle lineSpacing cause text to not fit UILabel

Henry Brown picture Henry Brown · Apr 25, 2015 · Viewed 11.5k times · Source

I have created a normal UILabel and want to be able to add line spacing to the text which does into the UILabel.

Although when I do this it affects the adjustsFontSizeToFitWidth and it is no longer fitted to the UILabel.

Some code I have used:

        var userQuestionsAnswer = UILabel(frame: CGRectMake(0, 0, 20, 20))
        userQuestionsAnswer.font = UIFont(name: Font.GothamBlack, size: 15)
        userQuestionsAnswer.numberOfLines = 0
        userQuestionsAnswer.adjustsFontSizeToFitWidth = true

        var style = NSMutableParagraphStyle()
        style.lineSpacing = view.frame.size.height * 0.021
        style.alignment = NSTextAlignment.Center
        let attributes = [NSParagraphStyleAttributeName : style]
        var answerText = "This is the answer"

        self.userQuestionsAnswer.attributedText = NSAttributedString(string: answerText!, attributes:attributes)

Can anyone tell my why this is and how I get around it?

Answer

TomSawyer picture TomSawyer · Apr 13, 2016

Remove the NSMutableParagraphStyle and it will work. I don't know why but this attribute is the cause of breaking text font size adjustment.