我有 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];
}
谢谢。