无法更改NSMutableAttributedString的颜色

时间:2013-06-14 18:05:42

标签: iphone ios objective-c

我使用CoreText创建以下文本,该文本填充矩形并围绕我将插入图像的区域。

attrString = [[NSMutableAttributedString alloc] initWithString:string];
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef) attrString, CFRangeMake(0, attrString.length), kCTFontAttributeName, font);
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef) attrString, CFRangeMake(0, attrString.length), kCTForegroundColorAttributeName, ForegroundTextColor);
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef) attrString, CFRangeMake(0, attrString.length), kCTParagraphStyleAttributeName, paragraphStyle);

/* Get a framesetter to draw the actual text */
CTFramesetterRef fs = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) attrString);
CTFrameRef frame = CTFramesetterCreateFrame(fs, CFRangeMake(0, attrString.length), pathToRenderIn, NULL);

/* Draw the text */
CTFrameDraw(frame, ctx);

/* Draw the text */
CTFrameDraw(frame, ctx);

在后面的方法中,我使用附加语句来更改文本子集的颜色:

[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(startRangeValue, endRangeValue)];

不幸的是,颜色不会改变。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我正在添加我的评论作为答案,因为它解决了问题:

将属性添加到字符串后,您必须重绘。基本上,您在屏幕上看到的不是可更改的NSString对象,而是它读取的对象的图形绘图。如果更改对象,则必须告诉它再次绘制对象。

因此问题的答案是,每当您尝试更改有关正在显示的字符串的任何内容时,您都需要调用绘图代码。