简体   繁体   中英

switch button's image on tap

I have the following code

- (IBAction)switchSetting:(UIButton *)sender {
    if([sender.currentImage isEqual:[UIImage imageNamed:@"settings_on"]]){
        [sender setImage:nil forState:UIControlStateNormal];
        //[sender setImage:[UIImage imageNamed:@"settings_off"] forState:UIControlStateHighlighted];
        [sender setTintColor:[UIColor clearColor]];
    }else{
        [sender setImage:[UIImage imageNamed:@"settings_on"] forState:UIControlStateNormal];
        //[sender setImage:[UIImage imageNamed:@"settings_on"] forState:UIControlStateSelected];
        //[sender setImage:[UIImage imageNamed:@"settings_on"] forState:UIControlStateReserved];
        //[sender setImage:[UIImage imageNamed:@"settings_on"] forState:UIControlStateHighlighted];
        [sender setTintColor:[UIColor clearColor]];
    }
}

All buttons background images are set to "settings_off". That way when I want to switch the settings I either set the buttons image to "settings_on" or NIL.

Problem is when I run the app, the buttons that has an image set to "settings_on" work fine (well, one problem is I need to click twice the first time to make the switch, but thats minor for now) but the buttons without an image set never switch. I have tried settings the images for the various states (selected, highlighted, normal), when I do this, then after the switch from on to off(nil), it won't switch back (as opposed to when being commented out). Im lost, any help appreciated thanks!

EDIT: Clearing all buttons from their backgroundImages, and only using "image" got it working; even though I still don't understand why my initial approach shouldn't be working. AFAIK the image view will overlay the background view... Does anybody know why I have to click twice the first time to get the switch going?

Have you tried the below code?

- (IBAction)switchSetting:(UIButton *)sender {
if([sender backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"settings_off"] ){
    [sender setImage:[UIImage imageNamed:@"settings_on"] forState:UIControlStateNormal];
}else{
    [sender setImage:[UIImage imageNamed:@"settings_off"] forState:UIControlStateNormal];
}

You can check UIButton Image with sender.currentImage :

- (IBAction)switchSetting:(UIButton *)sender {

if ([sender.currentImage isEqual:[UIImage imageNamed:@"settings_off"]]) 
{
[sender setImage:[UIImage imageNamed:@"settings_on"] forState:UIControlStateNormal];

}
else
{
[sender setImage:[UIImage imageNamed:@"settings_off"] forState:UIControlStateNormal];


}

}

Hope this will help you in checking button current image .

您可以尝试相应地在按钮上设置tag值,然后再使用switch语句检查条件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM