Matt Gomes
Matt Gomes

Reputation: 91

IPhone: Change line spacing in UITextView?

I've been looking all over the 'net for information/examples...

I'm trying to change the line spacing of text inside a UITextView object to double spaced. I thought you could do it via Core Text, but haven't found a solution!

Any example code or information would be greatly appreciated! Thanks!

Upvotes: 6

Views: 5107

Answers (3)

Radagast the Brown
Radagast the Brown

Reputation: 397

You can use NSLayoutManagerDelegate. Add that delegate to your ViewController or UIView class (etc.) and then when you create your UITextView...

yourTextView.layoutManager.delegate = self

Add this delegate method:

func layoutManager(layoutManager: NSLayoutManager, lineSpacingAfterGlyphAtIndex glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat {
    return 5 //Whatever you'd like...
}

Upvotes: 3

Mark Suman
Mark Suman

Reputation: 10460

This question was asked before iOS 6. I'd like to post an updated answer for those who would like a way to do this.

This can be done now with iOS 6 and later by using an NSAttributedString. UITextView now accepts an attributed string as one of its properties. You can do all sorts of text manipulation with attributed strings, including line spacing. You can set the min and max line heights for the paragraph style attribute of the string.

Check out the NSAttributedString Class Reference for more information.

Here's a sample of what you could do:

NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.minimumLineHeight = 21.0f;
paragraph.maximumLineHeight = 21.0f;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Test text line 1\nTest text line 2\nTest text line 3" attributes:@{NSParagraphStyleAttributeName: paragraph}];
textView.attributedText = attributedString;

Upvotes: 5

Ole Begemann
Ole Begemann

Reputation: 135550

You don't have to look all over the net. A look at the documentation for UITextView is sufficient to determine that changing the line spacing is not supported by that control.

With Core Text you have complete control over the layout of the text you draw, of course. But it would be a lot of work to rewrite a UITextView-like control from scratch.

Upvotes: 5

Related Questions