NSParagraphStyle line spacing ignored

borrrden picture borrrden · Sep 24, 2012 · Viewed 40.2k times · Source

A simple test that is failed: Make a new project with just one subview (UITextView) and put the following in:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple = 50.f;
    paragraphStyle.lineSpacing = 100.f;
    paragraphStyle.minimumLineHeight = 200.f;
    paragraphStyle.maximumLineHeight = 500.f;

    UIFont *font = [UIFont fontWithName:@"AmericanTypewriter" size:24.f];

    self.textView.attributedText = [[NSAttributedString alloc] initWithString:
    @"This is a test.\n Will I pass?" attributes:
    @{NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName : font}];
}

Line spacing is the same as if the attribute were not there. Has anything got this to work successfully? I put in ridiculous numbers just to show that it won't change...

Answer

Cocoanetics picture Cocoanetics · Dec 16, 2012

This is a bug in NSHTMLWriter which is the private class which UITextView uses to convert attributedText into HTML. Internally it displays this HTML via a UIWebDocumentView. Read more on the inner workings of UITextView in my writeup here: http://www.cocoanetics.com/2012/12/uitextview-caught-with-trousers-down/

The problem comes from an easy to miss speciality in the font CSS shorthand. If you specify a pixel size with the font shorthand then this sets BOTH the font-size as well as the line-height. Since NSHTMLWriter puts the font AFTER the line-height this causes the line-height to be cancelled out by the font size.

See here for my Radar which includes the full analysis of the bug: http://www.cocoanetics.com/2012/12/radar-uitextview-ignores-minimummaximum-line-height-in-attributed-string/

I suggest you file a bug report as well and mention my Radar #12863734.