uitableview – 在iOS 8上显示NSMutableAttributedString

看起来在iOS 8.0(12A365)NSMutableAttributedString有时不会显示正确.当文本的开头没有开始属性的范围(如果文本开头没有其他属性)时,这个问题显然是出现的.

所以用1.)第二个单词“green”不会显示绿色背景(bug!)(“cell”是一个UITableViewCell,UILabel“label”作为子视图):

1.)

text = [[NSMutableAttributedString alloc] initWithString:@"Green is green. (-> Bug)"];
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:(NSRange){9,5}];
cell.label.attributedText=text

使用2.)和3.)背景显示正确:

2.)

text = [[NSMutableAttributedString alloc] initWithString:@"Green is green. (-> Ok)"];
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:(NSRange){0,5}];
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:(NSRange){9,5}];
cell.label.attributedText=text

3.)

text = [[NSMutableAttributedString alloc] initWithString:@"Green is green. (-> Ok)"];
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:(NSRange){0,5}];
cell.label.attributedText=text

查找截图和XCode 6项目在这里Screenshot and XCode 6 Project

对我来说似乎是iOS 8中的一个bug – 所以报告给了苹果.

解决方法

尝试这样做,首先在整个标签中使用透明颜色应用一个额外的NSBackgroundColorAttributeName
text = [[NSMutableAttributedString alloc] initWithString:@"Green is green. (-> Bug)"];
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor clearColor] range:(NSRange){0,text.length}]; //Fix
[text addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:(NSRange){9,5}];
cell.label.attributedText=text

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...