Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the image of an UIImage view with a button

Hey, I have an ImageView in my app and I want the user to be able to change the image in that image view by clicking on a button.This is the code I got

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 for each image by the way!

The app builds but when I click on either one of the buttons nothings happens.

like image 935
Tapy Avatar asked Feb 11 '11 19:02

Tapy


2 Answers

Replace

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

and

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

with

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

and

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

Now it should work fine :)

like image 104
inFever Avatar answered Nov 16 '22 03:11

inFever


Simply set the image property of the UIImageView:

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

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

If I were designing this class, I'd 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, the tag would be 0, while the second would 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
like image 32
Jacob Relkin Avatar answered Nov 16 '22 03:11

Jacob Relkin