3

There are many places in my app that needs to set the UIColor. I want to define the color somewhere that I can reuse it without writing the same line again, it's hard to keep track and maintain.

UIColor *myColor = [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1];

I tried to make it like

#define myColor = [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1];

and reuse myColor but it doesn't work. :/

Thanks!

sonoluminescence
  • 1,002
  • 1
  • 11
  • 28
  • This is a duplicate question, take a look at this answer here - http://stackoverflow.com/questions/2824187/objective-c-defining-uicolor-constants – Chris Grant Dec 01 '11 at 10:08

2 Answers2

10

For your define, you could write:

#define myColor [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1]

and where you use myColor, it'll be replaced outright with [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1].

Alternatively, you could write a category on UIColor that provides a method that returns your colour.

Example:

@interface UIColor (MyColors)

+ (UIColor *)myAwesomeColor;

@end

@implementation UIColor (MyColors)

+ (UIColor *)myAwesomeColor
{
    return [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1];
}

@end

You would then use this like [UIColor myAwesomeColor] wherever you need it, just like you do with [UIColor blackColor].

Jasarien
  • 58,279
  • 31
  • 157
  • 188
0

answer given by mr Jasarien correct you can also follow above code and example

while declaring any thing in macro directives we don't assign any value so we cant use equal operators in directives "="sign you can use code like this #define mycolor [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1];