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

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...