How to add spacing to lines in NSAttributedString
The following sample code uses paragraph style to adjust spacing between paragraphs of a text.
UIFont *font = [UIFont fontWithName:fontName size:fontSize];NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight;NSDictionary *attributes = @{NSFontAttributeName:font, NSForegroundColorAttributeName:[UIColor whiteColor], NSBackgroundColorAttributeName:[UIColor clearColor], NSParagraphStyleAttributeName:paragraphStyle, };NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
To selectively adjust spacing for certain paragraphs, apply the paragraph style to only those paragraphs.
Hope this helps.
Great answer @Joe Smith
In case anyone would like to see what this looks like in Swift 2.*:
let font = UIFont(name: String, size: CGFloat) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight let attributes = [NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle] let attributedText = NSAttributedString(string: String, attributes: attributes) self.textView.attributedText = attributedText
Here is Swift 4.* version:
let string = """ A multiline string here """let font = UIFont(name: "Avenir-Roman", size: 17.0)let paragraphStyle = NSMutableParagraphStyle()paragraphStyle.paragraphSpacing = 0.25 * (font?.lineHeight)!let attributes = [NSAttributedStringKey.font: font as Any, NSAttributedStringKey.paragraphStyle: paragraphStyle]let attrText = NSAttributedString(string: string, attributes: attributes)self.textView.attributedText = attrText