How to set global variable with UIColor class

2019-05-06 08:46发布

i am developing on iPhone application. in this app i have 4 different views. in all views i set background color. see bellow code

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

i am testing various colors for background color. when i have to change any colour i need to change in all view controllers. instead of that can i make global variable for this ? i don't know how to set UIColor in global variable. please suggest me some ideas.

3条回答
贼婆χ
2楼-- · 2019-05-06 09:20

create constant.h file of NSObject and define this color globally

#define globalColor [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f];

and when you want to use it just import the constant file other wise 2 option is bellow..

Second Option

in AppDelegate.h file just property synthesize one variable of UIColor like bellow..

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
   ///your Data
   UIColor *globalColor;
}

@property (nonatomic,retain)  UIColor *globalColor;

and synthesize in .m file like bellow..

@syntesize globalColor;

and in didFinishLaunchingWithOptions method just asssign color to this variable..

- (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];

}

and when you want to use this color use like this..

    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
   self.view.backgroundColor = appDelegate.globalColor;
查看更多
萌系小妹纸
3楼-- · 2019-05-06 09:29

Better than using a global variable is to extend UIColor. Make a category with a constructor, that provides your color:

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];
 }
查看更多
淡お忘
4楼-- · 2019-05-06 09:37

Very simple.
In AppDelegate.h:

#define kGlobalColor [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f]

In ViewControllers:

#import "AppDelegate.h"

self.view.backgroundColor = kGlobalColor;
查看更多
登录 后发表回答