![](/img/trans.png)
[英]Why does this call to NSMutableAttributedString addAttributes crash?
[英]NSMutableAttributedString can't setAttributes or addAttributes correctly
我下面有一个方法可以用来更改UILabel
文本的最后6个字符的颜色,这将是括号中的日期,即(1999)
。 首先,我设置一个tableViewCell
的文本,然后获取attributedText
属性,以便获得UILabel
文本的字体和大小。 我不确定自己在做什么错,但是现在整个字符串都是黄色的,而不仅仅是标签文本的最后6个字符。 有什么想法吗?
tableViewCell.titleLabel.text = speech.title;
NSAttributedString *titleAttributedString = tableViewCell.titleLabel.attributedText;
tableViewCell.titleLabel.attributedText = [speech titleAttributedString:titleAttributedString size:tableCell.titleLabel.font.pointSize];
// Speech class instance method
- (NSAttributedString *)titleAttributedString:(NSAttributedString *)attributedString size:(CGFloat)size {
NSRange range = NSMakeRange(attributedString.length - 6, 6);
NSMutableAttributedString *titleString = [attributedString mutableCopy];
NSDictionary *titleAttributesDictionary = [attributedString attributesAtIndex:0 effectiveRange:&range];
NSDictionary *dateAttributesDictionary = @{
NSFontAttributeName : titleAttributesDictionary[NSFontAttributeName],
NSForegroundColorAttributeName : [UIColor yellowColor]
};
// Neither of these lines solves the problem
// Both titleStrings are yellow
[titleString setAttributes:dateAttributesDictionary range:range];
[titleString addAttributes:dateAttributesDictionary range:range];
[titleString setAttributes:dateAttributesDictionary range:range];
return titleString;
}
您将覆盖attributesAtIndex:effectiveRange:
调用中的计算range
值。 该调用要求索引0处的属性以及应用这些属性的有效范围,即整个字符串。 如果您对值不感兴趣(只是在索引0处的字体之后),则按docs传递NULL
到effectiveRange:
参数。
高温超导
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.