开发者

How to share constants between Interface Builder and the code?

I wonder if there is a way to use constants in Interface Builder, in order to avoid manually setting the same color at different places for example (it could be a very tedious job sometimes...)

Currently I set the color in the code and use #define to setup the color, but obviously I开发者_如何学CB can't use #define...


I have worked around this issue by subclassing the various controls to ensure the same style throughout the app. The drawback is that you can not see the style in interface builder only a wireframe.

For example I have a

@interface MyButton : UIButton 
@end


@implementation MyButton

 -(void) initialize{
self.backgroundColor = [UIColor MyButonColor]; // Using a category on UIColor
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self)  {
        [self initialize];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        [self initialize];
    }
    return self;
}


I think the easiest way to do this would be to create a category on the UIColor class and create a class method on it. For example:

Place this in a header file (e.g. UIColor+CustomColors.h):

@interface UIColor ( CustomColors )
+ (UIColor *)myCustomColor;
@end

Place this in an implementation file (e.g. UIColor+CustomColors.m)

@implementation UIColor ( CustomColors )
+ (UIColor *)myCustomColor
{
   return [UIColor colorWithRed:0.2 green:0.5 blue:0.2 alpha:1.0];
}
@end

Then you have access to the class method anywhere in your code like so:

...
self.view.backgroundColor = [UIColor myCustomColor];
...

See Apple's documentation on Categories for more info.

Alternatively, you can save swatches of color through the system color palette. To do this you simply call up the system color palette, select a color and drag it into the grid of colors.

These colors are now available in not only every Interface Builder document you create, but any application that makes use of the system color palette.

color palette http://img.skitch.com/20091030-dhh3tnfw5d8hkynyr7e5q3amwg.png

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜