我有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];
}
謝謝。
呵呵,今天是重構日。剛剛回答了10分鐘前的類似問題。 – 2013-02-09 22:30:04
BTW:使用數組來存儲按鈕,然後**使用**操作方法的'sender'參數。 – 2013-02-09 22:30:31
@ H2CO3謝謝你的洞察力。您的重構答案對我的代碼的其他部分非常有用! – askingtoomuch 2013-02-10 02:08:57