简体   繁体   English

NSMutableAttributedString - NSForegroundColorAttributeName

[英]NSMutableAttributedString - NSForegroundColorAttributeName

I am trying to set the color of all the ranges in my array but I am getting this error. 我试图设置我的数组中的所有范围的颜色,但我收到此错误。 I don't understand why. 我不明白为什么。 the ranges are all valid. 范围都是有效的。 I even tried manually inserting a range to test it. 我甚至尝试手动插入一个范围来测试它。 Thank You. 谢谢。

CGContextSetFillColorWithColor: invalid context 0x0 CGContextSetFillColorWithColor:无效的上下文0x0

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:tv.text];

for (NSString * s in array) {
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSRangeFromString(s)];
}

CATextLayer *textlayer = [[CATextLayer alloc]init];
textlayer.frame = CGRectMake(0, 0, 320, 480);
[self.view.layer addSublayer:textlayer];
textlayer.string = @"aString"; //works
textlayer.string = string; //does not work
tv.text = @"";

Is the code example the exact same code as you are trying to build? 代码示例是否与您尝试构建的代码完全相同? Im quite sure NSForegroundColorAttributeName is only available in Mac OS X SDK and iOS 6.0 and later so the example code should not even compile. 我非常确定NSForegroundColorAttributeName仅在Mac OS X SDK和iOS 6.0及更高版本中可用,所以示例代码甚至不应该编译。

What you want instead is probably kCTForegroundColorAttributeName and pass a CGColorRef instead of a NSColor . 您想要的可能是kCTForegroundColorAttributeName并传递CGColorRef而不是NSColor

[string addAttribute:(id)kCTForegroundColorAttributeName
               value:(id)[UIColor redColor].CGColor
               range:NSRangeFromString(s)];

But im not sure if this really is the cause of the invalid context error. 但我不确定这是否真的是无效上下文错误的原因。

Your context is wrong, not your range. 你的背景是错误的,不是你的范围。 You're trying to set the color of something that doesn't have a color. 你试图设置没有颜色的东西的颜色。

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

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