我想知道是否有办法在 Interface Builder 中使用常量,例如为了避免在不同的地方手动设置相同的颜色(有时这可能是一项非常乏味的工作......)
目前我在代码中设置颜色并使用#define设置颜色,但显然IB不能使用#define ...
我通过子类化各种控件来解决这个问题,以确保整个应用程序的风格相同。缺点是您无法在界面生成器中仅看到线框样式。
例如我有一个
@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;
}
我认为最简单的方法是在 UIColor 类上创建一个类别并在其上创建一个类方法。例如:
将其放在头文件中(例如 UIColor+CustomColors.h):
@interface UIColor ( CustomColors )
+ (UIColor *)myCustomColor;
@end
将它放在一个实现文件中(例如 UIColor+CustomColors.m)
@implementation UIColor ( CustomColors )
+ (UIColor *)myCustomColor
{
return [UIColor colorWithRed:0.2 green:0.5 blue:0.2 alpha:1.0];
}
@end
然后您可以在代码中的任何位置访问类方法,如下所示:
...
self.view.backgroundColor = [UIColor myCustomColor];
...
有关更多信息,请参阅Apple 关于类别的文档。
或者,您可以通过系统调色板保存颜色样本。为此,您只需调用系统调色板,选择一种颜色并将其拖到颜色网格中。
这些颜色现在不仅可以在您创建的每个 Interface Builder 文档中使用,而且可以在任何使用系统调色板的应用程序中使用。
调色板 http://img.skitch.com/20091030-dhh3tnfw5d8hkynyr7e5q3amwg.png