【问题标题】:Why does UITextView combine attributes from previously set attributedText? [closed]为什么 UITextView 会结合之前设置的属性文本的属性? [关闭]
【发布时间】:2012-10-19 02:13:21
【问题描述】:

在使用 NSAttributedString 时,我遇到了 UITextView 的一些奇怪行为。假设我有两个属性:

@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UITextView *textView;

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

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;

在模拟器中运行时,标签看起来(呃,发挥你的想象力)如下,使用系统默认字体:

<black>Hel</black><yellow>lo wh</yellow><black>ere?</black>

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

<red>Hel</red><yellow>lo wh</yellow><red>ere?</red>

似乎文本视图正在组合来自两个属性字符串的属性。我发现这是一个令人惊讶的结果,并希望它表现得像标签一样。

我怀疑这是一个错误。如果不是,那么 UITextView 如何以及为什么以与 UILabel 不同的方式对待属性文本?

(XCode 版本 4.5.1)

【问题讨论】:

  • 投票结束,因为问题是“为什么 API 是这样的”,没有人能回答这个问题。 API就是这样。我已经解释了如何使用它来解决您描述的行为;这就是任何人都可以做的。
  • 因不具建设性而关闭???版主的权利必须受到限制。

标签: ios uilabel uitextview nsattributedstring


【解决方案1】:

我向 Apple 提交了错误报告。他们回来说,iOS 7 beta 1 解决了这个问题。验证为已修复。

【讨论】:

  • 在我的机器上,使用 Xcode 4.5.2,文本视图保留了 20.0 的字体大小。此外,我认为 Xcode 中的更改不会改变这种行为。更改需要在 system (iOS) 中。
【解决方案2】:

我很确定这不是错误。文档明确指出:

分配一个新的值 [给文本视图的attributedText] 会更新字体、textColor 和 textAlignment 属性中的值,以便它们反映属性字符串中从位置 0 开始的样式信息。

因此,您未明确设置的任何属性都将从文本视图的整体属性继承,这些属性由先前的属性文本设置。

因此,正确的做法是在进行第二次分配之前重置字体、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;

【讨论】:

  • “明确声明”并不意味着它不接受解释:-)。无论如何,这并不能解释为什么 UITextField 和 UILabel 行为不同。如果没有错误,你能解释一下区别吗?
  • 假设我想将其他属性应用于 self.tv.attributedText。我认为我不能像以前那样只分配给它,我必须以某种方式连接?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
相关资源
最近更新 更多