Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add spacing to lines in NSAttributedString

I am making an app that formats screenplays, I am using a NSAttributedString to format the text entered into a UITextView, but some of the lines are too close together.

I was wondering if anyone could provide a code example or a tip on how to alter the margin between these lines so there is more space between them.

Below is an image of another desktop screenwriting program that demonstrates what I mean, notice how there is a bit of space before each bit where it says "DOROTHY".

enter image description here

like image 821
James Campbell Avatar asked Sep 07 '25 14:09

James Campbell


2 Answers

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.

like image 128
Joe Smith Avatar answered Sep 09 '25 19:09

Joe Smith


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
like image 33
Nathaniel Avatar answered Sep 09 '25 19:09

Nathaniel