How can I set the color and alignment of attributed text in a UITextView in iOS 7?

Joe picture Joe · Oct 13, 2013 · Viewed 46.9k times · Source

The formatting of my textViews worked fine in iOS 6, but no longer in iOS 7. I understand with Text Kit much of the under the hood stuff has changed. It's become really quite confusing, and I'm hoping someone can help straighten it out a bit by helping me with something as simple as this.

My static UITextView originally was assigned a value for it's textColor and textAlignment properties. Then I made a NSMutableAttributedString, assigned it an attributes, then assigned it to the textView's attributedText property. The alignment and color no longer take effect in iOS 7.

How can I fix this? If these properties take no effect, than why do they exist anymore? Here's the creation of the textView:

UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];

NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSParagraphStyleAttributeName value:font range:NSMakeRange(0, title.length)];
titleView.attributedText = title;

[self.view addSubview:titleView];

Answer

jlhuertas picture jlhuertas · Oct 13, 2013

Curious, the properties are taken into account for UILabel but not for UITextView

Why don't you just add attributes for color and alignment to the attributed string similar to the way you are doing with the font?

Something like:

NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];

//add color
[title addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, title.length)];

//add alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[title addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, title.length)];

titleView.attributedText = title;

Edit: Assign the text first, then change the properties and this way it works.

UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];

//create attributed string and change font
NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];

//assign text first, then customize properties
titleView.attributedText = title;
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];