change image on click of button in objective c

前端 未结 3 497
粉色の甜心
粉色の甜心 2021-01-27 15:51

i draged 3 button in my .xib file (btn1,btn2,btn3 respectively) and initially i given default image to them, first.png

now when user clicks on btn1, image of btn1 should

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-27 16:03

        #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
    

    inside the Implement file of the viewController

    - (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;
    
        }
    }
    

提交回复
热议问题