sdlabs
sdlabs

Reputation: 33

Changing UIImageView with button

I am wanting to press a button and alternate between two images with one UIImageView.

Right now when I run it, I press the button, the image changes but will not change back. What do I need to change in this action code to make it alternate?

- (IBAction)Change:(id)sender {
   image.image = [UIImage imageNamed:@"car.png"];

}

Upvotes: 1

Views: 1915

Answers (3)

Devang
Devang

Reputation: 11338

Try following code :

- (IBAction)Change:(id)sender {

        if ([sender isSelected]) 
        {  
          imageView.image = [UIImage imageNamed:@"car.png"];
          [sender setSelected:NO];  
        }
        else 
        {     
          imageView.image = [UIImage imageNamed:@"bike.png"];
          [sender setSelected:YES]; 
        }
}

To Display sequence image on button click.

.h file :

int counter;

.m file :

in viewDidLoad initialize counter = 0

Then

- (IBAction)Change:(id)sender {  
     counter++;
     imgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png",counter]];
}

And give your image name like 1.png, 2.png, 3.png and so on...

Upvotes: 4

Jani Baloch
Jani Baloch

Reputation: 40

You want that on button click you need another image you have to first set the image when you load the view and then on button click.

Upvotes: 0

ipraba
ipraba

Reputation: 16543

You have to maintain a flag.

In Somewhere before tapping the button, assign the flag

  BOOL isFirstImageShown=YES;

Then on your button action

- (IBAction)Change:(id)sender {
   if(isFirstImageShown)
   {
      isFirstImageShown=NO;
      yourImageView.image = [UIImage imageNamed:@"yourSecondImage.png"];
   }
   else
   {
     isFirstImageShown=YES;
     yourImageView.image = [UIImage imageNamed:@"yourFirstImage.png"];
   }
}

Upvotes: 1

Related Questions