简体   繁体   中英

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

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.

What you want instead is probably kCTForegroundColorAttributeName and pass a CGColorRef instead of a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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