点击目标c中的按钮更改图像

我在我的.xib文件中放了3个按钮(分别是btn1,btn2,btn3),最初我给它们提供了默认图像,first.png

现在当用户点击btn1时,btn1的图像应该从first.png变为second.png ..

当用户在btn2上选择时,btn2的图像应该从first.png变为second.png,并且还将btn1的图像再次更改为默认first.png,以便用户知道他已经点击了第二个按钮。

我该怎么办?

提前致谢 !!

您必须设置按钮操作方法代码

-(IBAction)btnClked:(id)sender { [btn1 setImage:[UIImage imageNamed:@"first.png"] forState:UIControlStateNormal]; [btn2 setImage:[UIImage imageNamed:@"first.png"] forState:UIControlStateNormal]; [btn3 setImage:[UIImage imageNamed:@"first.png"] forState:UIControlStateNormal]; UIButton *btn=(UIButton *)sender; [btn setImage:[UIImage imageNamed:@"second.png"] forState:UIControlStateNormal]; } 
  #import  @interface CustomRadioButton : UIButton { } @end #import "CustomRadioButton.h" @implementation CustomRadioButton - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // Set the refresh icon as the button's image [self setImage:[UIImage imageNamed:@"off.png"] forState:UIControlStateNormal]; [self setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateSelected]; // When the button is pressed, draw to button with less opacity. self.adjustsImageWhenHighlighted = YES; } return self; } @end 

在viewController的Implement文件中

 - (void)viewDidLoad { [super viewDidLoad]; for (int i=1;i<=2;i++){ CustomRadioButton *Radiobutton = [CustomRadioButton buttonWithType:UIButtonTypeCustom]; Radiobutton = [[CustomRadioButton alloc] initWithFrame:CGRectMake(200,50*i, 30, 30)]; [Radiobutton addTarget:self action:@selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside]; Radiobutton.tag=i; [self.view addSubview:Radiobutton]; } } - (IBAction)checkboxButton:(UIButton *)button{ for (UIButton *Radiobutton in [self.view subviews]) { if ([Radiobutton isKindOfClass:[UIButton class]] && ![Radiobutton isEqual:button]) { [Radiobutton setSelected:NO]; } } if (!button.selected) { button.selected = !button.selected; } } 

在按钮调用方法中设置图像,如:

 BOOL first; -(void)firstBtnPressed { if(first == YES){ [btn1 setImage:[UIImage imageNamed:@"first.png"] forState:UIControlStateNormal]; [btn2 setImage:[UIImage imageNamed:@"second.png"] forState:UIControlStateNormal]; first = NO; } else { first = YES; [btn1 setImage:[UIImage imageNamed:@"second.png"] forState:UIControlStateNormal]; [btn2 setImage:[UIImage imageNamed:@"first.png"] forState:UIControlStateNormal]; } }