我有3个按钮代表3个不同的图像。点击按钮时将显示图像。我的问题是,如何使用if()和NSArray / NSMutableDictionary / UIButton标签或其他方法来缩短代码。
- (id)initWithFrame:(CGRect)frame
{
_button1 = [UIButton buttonWithType:UIButtonTypeCustom];
_button1.frame = CGRectMake(20, 250, 50, 50);
[_button1 addTarget:self action:@selector(button1Tapped) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_button1];
_button2 = [UIButton buttonWithType:UIButtonTypeCustom];
_button2.frame = CGRectMake(140, 250, 50, 50);
[_button2 addTarget:self action:@selector(button2Tapped) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_button2];
_button3 = [UIButton buttonWithType:UIButtonTypeCustom];
_button3.frame = CGRectMake(210, 250, 50, 50);
[_button3 addTarget:self action:@selector(button3Tapped) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_button3];
}
- (void)button1Tapped
{
UIImage *_image = [UIImage imageNamed:@"IMAGE_1"];
_imageView = [[UIImageView alloc] initWithImage:_image];
_imageView.frame = CGRectMake(0, 0, 256, 384);
[self addSubview:_imageView];
}
- (void)button2Tapped
{
UIImage *_image = [UIImage imageNamed:@"IMAGE_2"];
_imageView = [[UIImageView alloc] initWithImage:_image];
_imageView.frame = CGRectMake(0, 0, 256, 384);
[self addSubview:_imageView];
}
- (void)button3Tapped
{
UIImage *_image = [UIImage imageNamed:@"IMAGE_3"];
_imageView = [[UIImageView alloc] initWithImage:_image];
_imageView.frame = CGRectMake(0, 0, 256, 384);
[self addSubview:_imageView];
}
感谢。
答案 0 :(得分:1)
像这样设置一组图像。把它变成你班上的财产。另外,也要尽早构建图像视图。
@property(nonatomic, strong) NSArray *images;
@property(nonatomic, strong) UIImageView *imageView;
- (id)initWithFrame:(CGRect)frame {
self.images = [NSArray arrayWithObjects:[UIImage imageNamed:@"IMAGE_1"], [UIImage imageNamed:@"IMAGE_2"], [UIImage imageNamed:@"IMAGE_3"], nil];
_imageView = [[UIImageView alloc] initWithImage:[self.images objectAtIndex:0]];
_imageView.frame = CGRectMake(0, 0, 256, 384);
[self addSubview:_imageView];
}
创建按钮时,请为它们添加标签......
_button1.tag = 1;
_button2.tag = 2;
_button3.tag = 3;
同样在创建按钮时,让他们都使用相同的选择器......
[_button1 addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];
[_button2 addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];
// etc
在点按上,tag-1将成为数组索引...
- (void)buttonTapped:(id)sender {
NSUInteger tag = ((UIButton *)sender).tag;
UIImage *image = [self.images objectAtIndex:tag];
self.imageView.image = image;
}