How to set global variable with UIColor class

对着背影说爱祢 提交于 2019-12-05 13:26:23

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;

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

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!