Globally declare UIColor in the project

Possible duplicate:
Objective C defining UIColor constants

I would like to use multiple colors throughout the application. Instead of creating a UIColor in every instance or all viewController, there is a way that I can use it throughout my application.

or it is reasonable to use the header file ColourConstants.h where I #define every color I want to use

ie

#define SCARLET [UIColor colorWithRed:207.0/255.0 green:47.0/255.0 blue:40.0/255.0 alpha:1];

      

early!

+3


source to share


2 answers


I would use a UIColor category. 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 if you want to use color, you only need to do this:



#import "UIColor+ScarletColor.h"

....

UIColor *scarlet = [UIColor scarletColor];

      

Hope it helps!

+22


source


The macro is more convenient because it is only defined in one place.

But it will still create a new instance every time it is used as a macro is just a text replacement for the pre-processor.

If you want to have a unique instance you will need to use FOUNDATION_EXPORT

(which means extern

).

In the publicly available .h file, declares the following:

FOUNDATION_EXPORT UIColor * scarlet;

      

This will tell the compiler that the variable scarlet

(of type UIColor

) will exist at some point (when the program is bound).
This way it will allow you to use it.



Then you need to create this variable in the .m file.
You cannot assign its value directly, as it is a runtime value, so just set it to nil:

UIColor * scarlet = nil;

      

And then, at some point in your program (perhaps in your application's div), set its value:

scarlet = [ [ UIColor ... ] retain ];

      

Remember to save it as it is a global variable that should live for the entire life of the program.

This way you only have one instance available externally.

+2


source







All Articles