问题
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