How to set global variable with UIColor class

回眸只為那壹抹淺笑 提交于 2019-12-07 11:27:55

问题


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.


回答1:


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;



回答2:


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



回答3:


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;


来源:https://stackoverflow.com/questions/13493598/how-to-set-global-variable-with-uicolor-class

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