开发者

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.


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 :)


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜