繁体   English   中英

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

[英]How to share constants between Interface Builder and the code?

我想知道是否有一种方法可以在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM