Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally declare UIColor in project [duplicate]

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!

like image 554
Sohan Avatar asked Nov 27 '22 22:11

Sohan


2 Answers

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!!

like image 192
Garoal Avatar answered Dec 11 '22 04:12

Garoal


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.

like image 21
Macmade Avatar answered Dec 11 '22 05:12

Macmade