Possible Duplicate:
Objective C defining UIColor constants
I'd like to use few colours throughout my app. Instead of creating a UIColor at every instance or in every viewController is there a way by which i can use it throughout the app.
or is it wise to use a ColourConstants.h header file where i #define each colour i want to use
i.e
#define SCARLET [UIColor colorWithRed:207.0/255.0 green:47.0/255.0 blue:40.0/255.0 alpha:1];
thanks in advance!
I would use a category on UIColor. For example:
// In UIColor+ScarletColor.h
@interface UIColor (ScarletColor)
+ (UIColor*)scarletColor;
@end
// In UIColor+ScarletColor.m
@implementation UIColor (ScarletColor)
+ (UIColor*)scarletColor {
return [UIColor colorWithRed:207.0/255.0 green:47.0/255.0 blue:40.0/255.0 alpha:1];
}
@end
And when you want to use the color you only have to do this:
#import "UIColor+ScarletColor.h"
....
UIColor *scarlet = [UIColor scarletColor];
Hope it helps!!
A macro is more convenient, as it's defined only in one place.
But it will still create a new instance, every time it's used, as a macro is just text replacement for the pre-processor.
If you want to have a unique instance, you'll have to use FOUNDATION_EXPORT
(which means extern
).
In a public .h file, declares the following:
FOUNDATION_EXPORT UIColor * scarlet;
This will tell the compiler that the scarlet
variable (of type UIColor
) will exist at some point (when the program is linked).
So it will allow you to use it.
Then you need to create that variable, in a .m file.
You can't assign its value directly, as it's a runtime value, so just set it to nil:
UIColor * scarlet = nil;
And then, at some point in your program (maybe in your app's delegate), set its value:
scarlet = [ [ UIColor ... ] retain ];
Do not forget to retain it, as it's a global variable which needs to live during the entire life-time of the program.
This way, you have only one instance, accessible from everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With