Change image of UIImage view using a button

Hey, I have an ImageView in my application, and I want the user to be able to change the image in this image view by clicking on the button. This is the code I received

In .h

@interface BGViewController : UIViewController { IBOutlet UIImageView *image; } @property (nonatomic, retain) IBOutlet UIImageView *image; -(IBAction)img1:(id)sender; -(IBAction)img2:(id)sender; 

and in .m

 @synthesize image; -(IBAction)img1:(id)sender; { UIImage *image = [UIImage imageNamed: @"Main.png"]; } -(IBAction)img2:(id)sender; { UIImage *image = [UIImage imageNamed: @"Themes.png"]; } 

There is one button between each button!

The application builds, but when I click on one of the buttons, nothing happens.

+7
source share
2 answers

Replace

 UIImage *image = [UIImage imageNamed: @"Main.png"]; 

and

 UIImage *image = [UIImage imageNamed: @"Themes.png"]; 

from

 image.image = [UIImage imageNamed:@"Main.png"]; 

and

  image.image = [UIImage imageNamed:@"Themes.png"]; 

Now it should work fine :)

+10
source

Just set the image property for UIImageView :

 imageView.image = [UIImage imageNamed:@"Themes.png"]; 

You also have a syntax error in implementing your method, getting rid of the semicolon ( ; ) after your method signatures.

If I were developing this class, I would use one action method and use the tag property of the sender argument to index into an array of NSString objects. (For the first button, tag will be 0 , and the second will be 1 , etc.)

You should rename your UIImageView ivar to imageView to reduce ambiguity.

 @interface BGViewController : UIViewController { IBOutlet UIImageView *imageView; } @property (nonatomic, retain) IBOutlet UIImageView *imageView; -(IBAction)changeImage:(id)sender; @end @implementation BGViewController NSString *images[] = { @"Main.png", @"Themes.png" }; @synthesize imageView; -(IBAction)changeImage:(id)sender { imageView.image = [UIImage imageNamed: images[sender.tag]]; } @end 
+3
source

All Articles