[英]NSMutableAttributedString can't setAttributes or addAttributes correctly
I have a method below that I want to use to change the color of the last 6 characters of a UILabel
's text, which will be a date in parenthesis, ie (1999)
. 我下面有一个方法可以用来更改
UILabel
文本的最后6个字符的颜色,这将是括号中的日期,即(1999)
。 First I set the text of a tableViewCell
and then I get the attributedText
property so I can get the font and size of the UILabel
text. 首先,我设置一个
tableViewCell
的文本,然后获取attributedText
属性,以便获得UILabel
文本的字体和大小。 I'm not sure what I'm doing wrong, but right now the whole string is yellow, not just the last 6 characters of the label's text. 我不确定自己在做什么错,但是现在整个字符串都是黄色的,而不仅仅是标签文本的最后6个字符。 Any ideas why?
有什么想法吗?
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;
}
You are overwriting your calculated range
value in the attributesAtIndex:effectiveRange:
call. 您将覆盖
attributesAtIndex:effectiveRange:
调用中的计算range
值。 That call asks for the attributes at index 0 and the effective range over which those attributes apply, which is your whole string. 该调用要求索引0处的属性以及应用这些属性的有效范围,即整个字符串。 Just pass
NULL
for the effectiveRange:
argument, as per the docs when you are not interested in the value (you're just after the font at index 0). 如果您对值不感兴趣(只是在索引0处的字体之后),则按docs传递
NULL
到effectiveRange:
参数。
HTH 高温超导
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.