November 17, 2020

Line spacing and font attribute in NSAttributedString

Sometimes line spacing from NSParagraphStyle is ignored with custom font attribute in UITextView. You can workaround this by using NSLayoutManagerDelegate. Here is example with bold font and 16 line spacing.

// ...

let font = UIFont.boldSystemFont(ofSize: 14)
let string = "First line\nSecond line\nThird line"

textView.layoutManager.delegate = self
textView.attributedText = NSAttributedString(
    string: string, 
    attributes: [.font: font]
)

// ...

extension MyView: NSLayoutManagerDelegate {
    
    func layoutManager(
        _ layoutManager: NSLayoutManager, 
        lineSpacingAfterGlyphAt glyphIndex: Int, 
        withProposedLineFragmentRect rect: CGRect
    ) -> CGFloat {
        return 16
    }
}
Example