【发布时间】:2010-12-10 18:44:27
【问题描述】:
我想知道是否有办法在 Interface Builder 中使用常量,例如为了避免在不同的地方手动设置相同的颜色(有时这可能是一项非常乏味的工作......)
目前我在代码中设置颜色并使用#define设置颜色,但是显然IB不能使用#define...
【问题讨论】:
标签: iphone interface constants builder
我想知道是否有办法在 Interface Builder 中使用常量,例如为了避免在不同的地方手动设置相同的颜色(有时这可能是一项非常乏味的工作......)
目前我在代码中设置颜色并使用#define设置颜色,但是显然IB不能使用#define...
【问题讨论】:
标签: iphone interface constants builder
我通过子类化各种控件来解决这个问题,以确保整个应用程序的风格相同。缺点是你不能在界面生成器中看到样式,只有一个线框。
例如我有一个
@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's documentation on Categories 了解更多信息。
或者,您可以通过系统调色板保存颜色样本。为此,您只需调用系统调色板,选择一种颜色并将其拖到颜色网格中。
这些颜色现在不仅可以在您创建的每个 Interface Builder 文档中使用,而且可以在任何使用系统调色板的应用程序中使用。
color palette http://img.skitch.com/20091030-dhh3tnfw5d8hkynyr7e5q3amwg.png
【讨论】: