如何使用UIColor类设置全局变量

4

我正在开发iPhone应用程序。在这个应用程序中,我有4个不同的视图。在所有视图中,我设置了背景颜色。见下面的代码

self.view.backgroundColor = [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f];

我正在测试不同的背景颜色。但每当我需要更改任何颜色时,我都必须在所有视图控制器中进行更改。是否可以创建全局变量来处理这个问题?我不知道如何设置 UIColor 的全局变量,请给我一些建议。

3个回答

9
非常简单。
在AppDelegate.h文件中:
#define kGlobalColor [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f]

在视图控制器中:

#import "AppDelegate.h"

self.view.backgroundColor = kGlobalColor;

我使用了上面的答案,但是出现了错误。 使用了未声明的标识符'kGlobalColor' - Bhavin_m
不要忘记在视图控制器中导入常量文件,在这种情况下是AppDelegate.h。 - pbibergal
谷歌搜索主题:如何正确定义Objective C - pbibergal

0
创建constant.h文件的NSObject并全局定义此颜色 #define globalColor [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f]; 当您想要使用它时,只需导入常量文件,否则以下是2个选项.. 第二个选项AppDelegate.h文件中,只需合成一个UIColor变量的属性,如下所示..
@interface AppDelegate : UIResponder <UIApplicationDelegate>{
   ///your Data
   UIColor *globalColor;
}

@property (nonatomic,retain)  UIColor *globalColor;

并在.m文件中合成如下所示的代码:

@syntesize globalColor;

didFinishLaunchingWithOptions 方法中将颜色分配给此变量。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
         globalColor = [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f];

}

当你想要使用这种颜色时,可以像这样使用。

    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
   self.view.backgroundColor = appDelegate.globalColor;

这是可行的,但不是最优的方法。 - pbibergal
哟,伙计,我也为此提供了另一种选择。我的第一个选择是常量文件,伙计。 :) - Paras Joshi

0
比使用全局变量更好的方法是扩展 UIColor。创建一个带有构造函数的类别,提供您的颜色:

UIColor+mycolor.h:

@interface UIColor (mycolor)
+ (UIColor*) myColor;
@end

UIColor+mycolor.m:

+ (UIColor*) systemBlue
{
return [UIColorcolorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f];
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接