0

I am trying to switch between two different images when clicking on a button. Below is the code I wrote so far. However, this will only display one image and not toggle between them.

-(IBAction)show {

    BOOL img = true;

    if (img = true) {
    UIImage *img1 = [UIImage imageNamed:@"UnCheck.png"];
    [imageview setImage:img1];
        }
    else {
        UIImage *img = [UIImage imageNamed:@"Check.png"];
        [imageview setImage:img];
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

1

You have a couple of issues with your code:

First, img is a local variable inside your tap handler, so each time that function runs, it will be set to true.

Second, your if statement actually contains an assignment (=) instead of a comparison (==), so even if img wasn't already true it would be when you execute the if statement.

All of this means that your image is always going to be UnCheck.png.

You need to use a property, outside the function, so that the state is tracked properly. img is also a pretty poor variable name, checked or isChecked is probably better.

Then your button handler method simply needs to toggle this property and set the appropriate image.

@property BOOL isChecked;

-(IBAction)show {
    self.isChecked = !self.isChecked;

    NSString *imageName = self.isChecked ? @"Check.png":@"UnCheck.png";
    UIImage *img = [UIImage imageNamed:imageName];
    [imageview setImage:img];
 }
Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • Thank you for the clarification! Helped me a lot – Teo Ohlsson Sep 01 '18 at 08:34
  • You can refactor it a little more by using image isHighlighted property too. Add following code where `imageview` initialized. `UIImageView(image: UIImage?, highlightedImage: UIImage?)` And use below in your `(IBAction)show` imageview.isHighlighted = self.isChecked – Satish Sep 01 '18 at 09:43