UIButton / Attributed Text - Varying line Spacing

35 Views Asked by At

I've got a component in a Swift 5 project inheriting from UIButton. The button has two sections of text: a heading (1 line) and a subheading (1+ lines). The two sections of text are formatted as a single attributed string which is used as the value for UIButton.titlelabel.

I need the line spacing between the title heading and subheading to be a value a, and the spacing between each line of the subheading to be a different value b. I've tried the following, to no avail (the spacing for the entire attributed text is set to the subtitle spacing). Is it possible to have a varying line height, or do I need a different approach?

let buttonText = NSMutableAttributedString()

let titleStyle = NSMutableParagraphStyle()
titleStyle.lineHeightMultiple = 1
        
let title = NSAttributedString(string: title,
                               attributes: [
                               NSAttributedString.Key.font: UIFont.title3,
                               NSAttributedString.Key.paragraphStyle: titleStyle
                               ])
buttonText.append(title)

let subtitleStyle = NSMutableParagraphStyle()
subtitleStyle.lineHeightMultiple = 0.7
            
let subtitle = NSAttributedString(string: subtitle,
                                  attributes: [
                                  NSAttributedString.Key.font: UIFont.body,
                                  NSAttributedString.Key.paragraphStyle: subtitleStyle
                                ])
            
buttonText.append(subtitle)
0

There are 0 best solutions below