IPhone: Change line spacing in UITextView?
Asked Answered
D

3

6

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!

Disqualify answered 29/9, 2010 at 17:24 Comment(0)
H
5

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.

Householder answered 29/9, 2010 at 19:28 Comment(1)
absolutely, as of iOS 4.3 UITextView does not support any line height changes.Oran
C
5

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;
Chancre answered 16/2, 2014 at 6:12 Comment(0)
W
3

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...
}
Wiese answered 3/2, 2016 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.