开发者

Objective C defining UIColor constants

I have a iPhone application with a few custom-defined colors for my theme. Since these colors will be fixed for my UI, I would like to define the colors in a class to be included (Constants.h and Constants.m). How do I do that? (Simply defining them do开发者_Python百科es not work because UIColors are mutable, and would cause errors - Initalizer not constant).

/* Constants.h */
extern UIColor *test;

/* Constants.m */
UIColor *test = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];

Thanks!


A UIColor is not mutable. I usually do this with colors, fonts and images. You could easily modify it to use singletons or have a static initializer.

@interface UIColor (MyProject)

+(UIColor *) colorForSomePurpose;

@end

@implementation UIColor (MyProject)

+(UIColor *) colorForSomePurpose { return [UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]; }

@end


For simplicity I did this:

/* Constants.h */
#define myColor [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0]

Don't forget to leave out the ';' so you can use it as a normal expression.

I'm not sure if there's anything technically wrong with this approach, but it works fine, and avoids the compile-time constant initializer error - this code is effectively stuck in place anywhere you put 'myColor', so it doesn't ever get compiled until you actually use it.


Another option

in your .h you can do

extern UIColor *  const COLOR_LIGHT_BLUE;

in your .mm you can do

UIColor* const COLOR_LIGHT_BLUE = [[UIColor alloc] initWithRed:21.0f/255 green:180.0f/255  blue:1 alpha:1];//;#15B4FF


If you're looking for a quick and dirty one without extensions go with clang:

#define kGreenColor colorWithRed:(0/255.0) green:(213/255.0) blue:(90/255.0) alpha:1.0

- (void)doSomething
{
   _label.textColor = [UIColor kGreenColor];

}


Often people put global constants into singleton objects - or as drawnonward noted, you can make them accessible via a class method of some class.


Here's another way:

Header:

#if !defined(COLORS_EXTERN)
    #define COLORS_EXTERN extern
#endif

COLORS_EXTERN UIColor *aGlobalColor;

Implementation:

#define COLORS_EXTERN
#import "GlobalColors.h"


@interface GlobalColors : NSObject
@end

@implementation GlobalColors

+ (void)load
{
    aGlobalColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.4 alpha:1];
}

@end

It's a bit of a hack, but you don't need to redefine the color in the implementation and you can access colors without a method call.


Use the AppController to make the colors accessible globally, rather than a static variable. That way it makes sense from an architecture standpoint, and also if you wanted to hypothetically change color schemes, even while running, this would just be a method or two on the AppController

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜