While playing around with NSAttributedString, I have run into some strange behavior from UITextView. Say I have two properties:
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UITextView *textView;
In the owning controller for these properties, I have the following code:
NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:20.],
NSForegroundColorAttributeName: [UIColor redColor]};
NSAttributedString *as = [[NSAttributedString alloc] initWithString:@"Hello there!" attributes:attributes];
NSMutableAttributedString *mas = [[NSMutableAttributedString alloc] initWithString:@"Hello where?" attributes:nil];
[mas addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(3, 5)];
self.label.attributedText = as;
self.label.attributedText = mas;
self.textView.attributedText = as;
self.textView.attributedText = mas;
When running in the simulator, the label looks (er, use your imagination) as follows, using the system default font:
<black>Hel</black><yellow>lo wh</yellow><black>ere?</black>
The text view looks as follows, using the system font in size 20.0:
<red>Hel</red><yellow>lo wh</yellow><red>ere?</red>
It seems like the text view is combining the attributes from the two attributed strings. I find this a surprising result, and expected it to behave like the label.
I suspect this is a bug. If it is not, how and why does UITextView treat attributedText differently than UILabel?
(XCode Version 4.5.1)
I'm pretty sure this is not a bug. The documentation clearly states:
assigning a new a value [to a text view's
attributedText
] updates the values in the font, textColor, and textAlignment properties so that they reflect the style information starting at location 0 in the attributed string.
Thus any properties that you do not set explicitly will be inherited from the overall properties of the text view, which were set by the previous attributed text.
Thus the correct way to do what you're trying to do is to reset the font, textColor, and textAlignment before making the second assignment:
self.tv.attributedText = as;
// reset everything
self.tv.text = nil;
self.tv.font = nil;
self.tv.textColor = nil;
self.tv.textAlignment = NSTextAlignmentLeft;
// and now... lo and behold ...
self.tv.attributedText = mas;
I filed a bug report with Apple. They came back and said that the issue was addressed with iOS 7 beta 1. Verified as fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With