UIColor,UIFont等的外部常量

Jim*_*Jim 7 cocoa cocoa-touch objective-c extern

我有一个constants.m文件,它是许多程序常量的集中集合.要设置颜色,我这样做:

@implementation UIColor (UIColor_Constants) 

+(UIColor *) defaultResultTableBackgroundColor{
    //return [[UIColor colorWithRed:0.6f green:0.004f blue:0.0f alpha:1.0f] retain];
    return [[UIColor colorWithRed:0.1f green:0.004f blue:0.3f alpha:0.3f] retain];
}

+(UIColor *) defaultResultHeaderBackgroundColor{
    return [[UIColor clearColor] retain];
}

@end
Run Code Online (Sandbox Code Playgroud)

在constants.h我有

@interface UIColor (UIColor_Constants) 

+(UIColor *) defaultResultTableBackgroundColor;
+(UIColor *) defaultResultHeaderBackgroundColor;

@end
Run Code Online (Sandbox Code Playgroud)

然后只使用[UIColor defaultResultTableBackgroundColor]我想引用此常量的位置.

我想有一些其他UIColor和UIFont常量,虽然这有效,但似乎比它需要的更复杂.有更简单的方法吗?

sup*_*ssi 9

我使用常量文件用于相同的目的.我没有设置整个接口和实现文件,而是将常量文件创建为标题(.h)文件.然后,我定义我想要使用的颜色,例如:

#define globalColor [UIColor colorWithRed:0.1f green:0.004f blue:0.3f alpha:0.3f]
Run Code Online (Sandbox Code Playgroud)

然后,任何时候你使用globalColor它就像键入定义的代码.


lbr*_*dnr 6

我其实也喜欢这种方式.一个问题:为什么你保留了uicolor?这非常危险.它很可能会犯错误并造成内存泄漏.

  • 如果将UIColor实例存储在静态变量中以便重用它,则保留UIColor实例将是正确的.事实上,你是对的:保留它然后只是返回它是不正确的. (2认同)

cds*_*per 6

这是一篇很好的解读,解释了Objective C中的常量:

在Objective-C中创建常量的最佳方法是什么

简短的回答:你正在以最好的方式处理这个问题.

不推荐使用宏.正如一些人所提到的,你可以#define一个宏来处理你的颜色.这基本上告诉预处理器在代码上运行查找和替换.这种方法有许多缺点,包括范围和类型.Apple明确建议不要使用这些类型的"常量":https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html

也可以创建一个常量:

(在标题中,文件范围)

extern UIColor *  const COLOR_LIGHT_BLUE;
Run Code Online (Sandbox Code Playgroud)

(在您的实现中,文件范围)

UIColor* const COLOR_LIGHT_BLUE = [[UIColor alloc] initWithRed:21.0f/255 green:180.0f/255  blue:1 alpha:1];
Run Code Online (Sandbox Code Playgroud)

当然,您可以在前缀标题中#import此标头以节省更多输入.但最终,它与你已经在做的事情相比并没有太大的改进.