问题
What is the best way to keep my UI constants in seperate class accesible from all controllers?
UIView, UIImage and UIColour all these images and colours create a such mess of allocations and releases in my controllers and most of them are even same. Instead of alloc/relase the same images and views, CAlayers over and over again in different classes, I want to create them once, cache them (or something like that) and easily access when needed.
I want to keep memory and my code clean.
回答1:
yes , its possible
create a class like gconstants , then store all your string here in h/m files
extern NSString *const APP_TITLE;
@interface UIColor (APP)
+(UIColor *) APP_NAV_COLOR;
@end
in .m file
NSString *const APP_TITLE = @"APP Name";
@implementation UIColor (APP)
+(UIColor *) APP_NAV_COLOR { return [UIColor colorWithRed:00/256.0 green:111/256.0
blue:59/256.0 alpha:1.0]; }
@end
and in any controller declare the header file
self.title = APP_TITLE;
回答2:
You could use some macro's defined in a header file which you can then include in all the appropriate implementation files, or even in your prefix.pch
if you want to make them available to every file in your project.
As an example, imagine a header file called Config.h
For a shared UIColor
you could add the following ...
#define SOME_CONSTANT_COLOR [UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:0.5f]
And then you can access it the same way as you would use any other macro ...
#import "Config.h" // at the top of you implmentation file, or prefix header
someView.backgroundColor = SOME_CONSTANT_COLOR;
The same also goes for images as well ..
#define SOME_IMAGE [UIImage imageNamed:@"someImage.png"]; // In config.h
myImageView.image = SOME_IMAGE; // In implementation file
来源:https://stackoverflow.com/questions/6911956/iphone-managing-reusable-uiimages-and-uiviews