How to set a global variable with the UIColor class

I am developing an application for the iPhone. In this application I have 4 different views. in all views, I set the background color. see below 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 different colors for background color. when I need to change any color that I need to change in all view controllers. instead, can i make a global variable for this? I do not know how to set UIColor in a global variable. please offer me some ideas.

+4
source share
3 answers

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; 
+9
source

create constant.h NSObject file 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 const file, another wise option 2 below.

Second option

in AppDelegate.h A simple file property synthesizes a single UIColor variable, as shown below.

 @interface AppDelegate : UIResponder <UIApplicationDelegate>{ ///your Data UIColor *globalColor; } @property (nonatomic,retain) UIColor *globalColor; 

and synthesize the .m file as shown below.

 @syntesize globalColor; 

and in didFinishLaunchingWithOptions method just sets the color of 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 if you want to use this color, use like this.

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

It is better to use a global variable - this is an extension of UIColor . Create a category with a constructor that provides 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]; } 
0
source

Source: https://habr.com/ru/post/1447483/


All Articles