Setting font on NSAttributedString on UITextView disregards line spacing

Snowman picture Snowman · Oct 2, 2012 · Viewed 136.7k times · Source

I'm trying to set an attributed string to a UITextView in iOS 6. The problem is, if I attempt to set the font property on the attributed string, the line spacing is ignored. However, if I don't set the font, and the default font is used, then line spacing works.

NSString *string = @" Hello \n world";
attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];

paragraphStyle.minimumLineHeight = 50;
// setting the font below makes line spacing become ignored
[attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, string.length)];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];

mainTextView.attributedText = attrString;

Any idea what's going on?

Answer

maxeng picture maxeng · Nov 9, 2012

Attributed String Programming Guide:

UIFont *font = [UIFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
                                forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil" attributes:attrsDictionary];

Update: I tried to use addAttribute: method in my own app, but it seemed to be not working on the iOS 6 Simulator:

NSLog(@"%@", textView.attributedText);

The log seems to show correctly added attributes, but the view on iOS simulator was not display with attributes.