Question

I'm trying to create a category to change the color of an existing NSAttributedString that is rendered in a CATextLayer. Here's the category implementation

@implementation NSAttributedString (_additions)

-(NSAttributedString*)attributedStringWithColor:(UIColor*)color{

    NSMutableAttributedString* mutableSelf = [self mutableCopy];

    [mutableSelf addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, mutableSelf.length)];

    return [mutableSelf attributedSubstringFromRange:NSMakeRange(0, mutableSelf.length)];

}
@end

The CATextLayer is in a subclass of CAShapeLayer. I should also mention that the CATextLayer does render with the correct attributes, EXCEPT the color.

// in .m

// class continuation:
    @interface ONCShapeLayerSubclass()
    {
        CATextLayer* textLayer;    
    }
    @end

@implementation
//...

-(void)update{

    // method that initializes the catextlayer 
    //...

    if(!textLayer){
        textLayer = [CATextLayer layer];
        textLayer.alignmentMode = kCAAlignmentCenter;
        textLayer.frame = self.bounds;
        textLayer.foregroundColor = [kDefaultLineColor CGColor];
        [self addSublayer:textLayer];
    }

    textLayer.string = //// a method that returns an attributed string from a database

   //...

    [self updateColor];
} 


-(void)updateColor{

     if(textLayer)textLayer.string = [textLayer.string attributedStringWithColor:kDefaultLineColor];
}

@end

The string shows up attributed EXCEPT for the color. And then I get a whole bunch of errors:

CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

Any ideas why it isn't working?

Was it helpful?

Solution

As far as I can tell, this is a bug with CATextLayer, and not with my code. It works correctly for text displayed in UILabels, just not in CATextLayers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top