Search code examples
iosios4

NSForegroundColorAttributeName undeclared


When using the below snippet, i get the undefined / undeclared error on

NSForegroundColorAttributeName

This is the url i referred

my code snippet

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:self.myDisplayTxt];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];

Please let me know


Solution

  • Try using kCTForegroundColorAttributeName.

    Your code

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:self.myDisplayTxt];
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    

    Make this change

    [string addAttribute:(NSString*)kCTForegroundColorAttributeName 
                    value:(id)[[UIColor redColor] CGColor]
                    range:NSMakeRange(0,5)];
    

    From sample code by apple,

    Add following after #import line to your .m file in which u use addAttribute:

    #if (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
    #import <CoreText/CoreText.h>
    #else
    #import <AppKit/AppKit.h>
    #endif
    

    Pls see if this helps. DONT FORGET TO ADD CORETEXT FRAMEWORK