1

在我们的应用程序中,我经常需要为按钮等 UI 元素加载图像。每个图像都有几种变体,例如横向/纵向、禁用/启用、推送/常规,甚至是白色/红色/灰色等颜色。加载代码有一些变量告诉它要加载哪个变体。例如,看一下以下示例按钮类:

enum {
    SampleImageButtonRed,
    SampleImageButtonWhite
} SampleImageButtonStyle;

@interface SampleImageButton : NSObject
@property(assign) SampleImageButtonStyle style;
@property(assign) BOOL landscape;
@property(assign) BOOL disabled;
@property(assign) BOOL pushed;
@end

这里加载代码必须根据按钮类型查看属性和 loadbutton_white_pushed.png等等。button_red_landscape.png代码在概念上很简单(只是一些字符串格式和[UIImage imageNamed:]调用),但同时有很多噪音和样板。

我试图想出一个简单的帮助类来让这更容易。该类将采用将属性映射到结果图像名称的规则,然后它将采用手头的实际属性值并返回适当的图像。就像是:

ImageBuilder *builder = [[ImageBuilder alloc] init];

[[[builder record] setPathTag:@"button_red"] setButtonStyle:SampleImageButtonRed];
[[[builder record] setPathTag:@"button_white"] setButtonType:SampleImageButtonWhite];

[[[builder record] setPathTag:@"disabled"] setDisabled:YES];
[[[builder record] setPathTag:@"enabled"] setDisabled:NO];

[[[builder record] setPathTag:@"landscape"] setLandscape:YES];
[[[builder record] setPathTag:@"portrait"] setLandscape:NO];

然后我会这样称呼:

// would load “button_red_enabled.png”
UIImage *texture = [[[builder image]
    setButtonStyle:SampleImageButtonRed]
    setDisabled:NO];

目前我对增加的复杂性是否值得感兴趣,我对 API 的设计和实现感兴趣。我认为“记录”API 可以工作,但“查询”API 不行,因为setButtonStyle:返回void,因此我无法链接调用或返回图像。

你有想法为这个问题提供一个很好的通用 API 吗?

4

0 回答 0