0

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

谢谢。

4

1 回答 1

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;
}
于 2013-02-09T23:48:03.613 回答