2014-01-27 38 views
0

我想创建一个类别来改变在CATextLayer中呈现的现有NSAttributedString的颜色。这里的类别执行改变现有NSAttributedString的颜色

@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 

的CATextLayer是CAShapeLayer的子类。我还应该提到CATextLayer的渲染具有正确的属性,除了颜色。

// 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 

该字符串显示归因于颜色除外。然后我收到一大堆错误:

CGContextSetFillColorWithColor:invalid context 0x0。这是一个严重的错误。此应用程序或其使用的库正在使用无效的上下文,从而导致系统稳定性和可靠性的整体降级。这个通知是礼貌的:请解决这个问题。这将成为即将到来的更新中的致命错误。

任何想法,为什么它不工作?

+0

显示你在哪里的代码_calling_' attributedStringWithColor:'。问题出在哪里 - 而不是你已经显示的代码。 – matt

+0

我编辑了这个问题。谢谢 – olynoise

+0

你确定'textLayer.string'是一个属性字符串吗?它可能是一个'NSString'。它也可能是'nil'。 –

回答

0

据我所知,这是CATextLayer的错误,而不是我的代码。它适用于在UILabels中显示的文本,而不是在CATextLayers中。