如何在Interface Builder和代码之间共享常量?

时间:2009-10-28 07:55:58

标签: iphone interface constants builder

我想知道是否有一种方法可以在Interface Builder中使用常量,以避免在不同的地方手动设置相同的颜色(有时候这可能是一项非常繁琐的工作......)

目前我在代码中设置颜色并使用#define设置颜色,但显然IB不能使用#define ...

2 个答案:

答案 0 :(得分:0)

我通过子类化各种控件来解决这个问题,以确保整个应用程序的样式相同。缺点是您无法在界面构建器中看到仅有线框的样式。

例如我有一个

@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;
}

答案 1 :(得分:-1)

我认为最简单的方法是在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

相关问题