繁体   English   中英

NSMutableAttributedString无法正确设置属性或添加属性

[英]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传递NULLeffectiveRange:参数。

高温超导

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM