25

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

James Campbell
  • 3,511
  • 4
  • 33
  • 50

3 Answers3

52

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.

Hemang
  • 26,840
  • 19
  • 119
  • 186
Joe Smith
  • 1,900
  • 1
  • 16
  • 15
20

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
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129
Nathaniel
  • 836
  • 9
  • 19
  • Nathaniel, this is almost perfect - except the paragraph style needs to be initialized as NSMutableParagraphStyle(). NSParagraphStyle is immutable so it's spacing properties are read only and can't be modified – Natalia Aug 23 '16 at 20:14
  • Good point, @NataliaChodelski! I had fixed it in my code but not in my post. I have made the change. :) – Nathaniel Aug 24 '16 at 16:02
10

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
enigma
  • 865
  • 9
  • 22