为什么UITextView结合了先前设置的attributionText的属性?

Mik*_*keG 9 uitextview nsattributedstring uilabel ios

在玩NSAttributedString时,我遇到了一些来自UITextView的奇怪行为.说我有两个属性:

@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UITextView *textView;
Run Code Online (Sandbox Code Playgroud)

在这些属性的拥有控制器中,我有以下代码:

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;
Run Code Online (Sandbox Code Playgroud)

在模拟器中运行时,标签使用系统默认字体查看(呃,使用您的想象力),如下所示:

<black>Hel</black><yellow>lo wh</yellow><black>ere?</black>
Run Code Online (Sandbox Code Playgroud)

使用大小为20.0的系统字体,文本视图如下所示:

<red>Hel</red><yellow>lo wh</yellow><red>ere?</red>
Run Code Online (Sandbox Code Playgroud)

看起来文本视图组合了两个属性字符串的属性.我发现这是一个令人惊讶的结果,并期望它表现得像标签.

我怀疑这是一个错误.如果不是,UITextView如何以及为什么以不同于UILabel的方式处理attributionText?

(XCode版本4.5.1)

mat*_*att 5

我很确定这不是一个bug.文件明确指出:

为文本视图分配新值[ attributedText]更新font,textColor和textAlignment属性中的值,以便它们反映从属性字符串中的位置0开始的样式信息.

因此,未显式设置的任何属性都将从文本视图的整体属性继承,这些属性由前一个属性文本设置.

因此,执行您要执行的操作的正确方法是在进行第二次分配之前重置font,textColor和textAlignment:

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;
Run Code Online (Sandbox Code Playgroud)


Mik*_*keG 4

我向 Apple 提交了错误报告。他们回来后表示,该问题已在 iOS 7 beta 1 中得到解决。已验证已修复。