Objective C defining UIColor constants

陌路散爱 提交于 2019-11-27 18:46:28

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
AmitP

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!