xcode 在项目中全局声明 UIColor
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10076670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Globally declare UIColor in project
提问by Sohan
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.
我想在整个应用程序中使用几种颜色。有一种方法可以让我在整个应用程序中使用它,而不是在每个实例或每个 viewController 中创建 UIColor。
or is it wise to use a ColourConstants.h header file where i #define each colour i want to use
或者使用 ColourConstants.h 头文件是明智的,我在其中 #define 我想使用的每种颜色
i.e
IE
#define SCARLET [UIColor colorWithRed:207.0/255.0 green:47.0/255.0 blue:40.0/255.0 alpha:1];
thanks in advance!
提前致谢!
回答by Garoal
I would use a category on UIColor. For example:
我会在 UIColor 上使用一个类别。例如:
// 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!!
希望能帮助到你!!
回答by Macmade
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
).
如果您想拥有一个唯一的实例,则必须使用FOUNDATION_EXPORT
(这意味着extern
)。
In a public .h file, declares the following:
在公共 .h 文件中,声明以下内容:
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.
这将告诉编译器scarlet
变量(类型UIColor
)将在某个时刻(当程序链接时)存在。
所以它会让你使用它。
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:
然后您需要在 .m 文件中创建该变量。
您不能直接分配它的值,因为它是一个运行时值,因此只需将其设置为 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.
这样,您只有一个实例,可以从任何地方访问。