Question

I am trying to use a UISwitch to show an image when on, and hide that image when off. I keep running into the issue where the image shows when the switch is turned on but it doesn't hide when the switch is turned off. I've tried a bunch of different solutions online but none seem to work.

This is one of the solutions I've tried. Is there another way to determine if the switch is on aside from switchname.on? Maybe if else statements aren't the way to go?

Any help is greatly appreciated!

@property(nonatomic, strong) UIImageView *spawnImage;


- (IBAction)changeSwitch:(id)sender{

UIImageView *spawnImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 300, 169)];

if(spawnPoints.on){
    NSLog(@"Switch is ON");
    [spawnImage setImage:[UIImage imageNamed:@"freight-spawn.png"]];

}

else{
    NSLog(@"Switch is OFF");
    [spawnImage setImage:[UIImage imageNamed:@"freight-none.png"]];

}

[self.view addSubview:spawnImage];
}

Update!

Thanks to @meda we figured out a solution.

.h

@interface ViewController: UIViewController {
    IBOutlet UIImageView *spawnImage;
}

.m

-(IBAction)changeSwitch:(id)sender{
if(spawnPoints.on){
    NSLog(@"Switch is ON");
    [spawnImage setImage:[UIImage imageNamed:@"freight-spawn.png"]];
}

else{
    NSLog(@"Switch is OFF");
    [spawnImage setImage:[UIImage imageNamed:@"freight-none.png"]];
}

[self.view addSubview:spawnImage];
}

Note that this is an IB solution where a blank UIImageView must be dragged in and position and hooked up to the outlet in connections.

Was it helpful?

Solution

Is there another way to determine if the switch is on aside from switchname.on?

Yes you can try isOn instead of on:

   if(spawnPoints.isOn){
        NSLog(@"Switch is ON");
        [spawnImage setImage:[UIImage imageNamed:@"freight-spawn.png"]];
    }
    else{
        NSLog(@"Switch is OFF");
        [spawnImage setImage:[UIImage imageNamed:@"freight-none.png"]];
    }

or

[spawnImage setImage:[UIImage imageNamed:spawnPoints.isOn?
                    @"freight-spawn.png": @"freight-none.png"]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top