问题
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 does 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!
回答1:
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
回答2:
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.
回答3:
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
回答4:
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];
}
回答5:
Often people put global constants into singleton objects - or as drawnonward noted, you can make them accessible via a class method of some class.
回答6:
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.
回答7:
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
来源:https://stackoverflow.com/questions/2824187/objective-c-defining-uicolor-constants