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中。