ios 使用按钮更改 UIImage 视图的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4973241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:52:14  来源:igfitidea点击:

Changing the image of an UIImage view with a button

objective-ciosuiimageviewuibutton

提问by Tapy

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

嘿,我的应用程序中有一个 ImageView,我希望用户能够通过单击按钮来更改该图像视图中的图像。这是我得到的代码

In .h

在.h

@interface BGViewController : UIViewController {

    IBOutlet UIImageView *image;

}

@property (nonatomic, retain) IBOutlet UIImageView *image;

-(IBAction)img1:(id)sender;
-(IBAction)img2:(id)sender;

and in .m

并在.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.

该应用程序构建但是当我单击其中一个按钮时什么也没有发生。

回答by inFever

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

现在它应该可以正常工作了:)

回答by Jacob Relkin

Simply set the imageproperty of the UIImageView:

只需设置 的image属性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 tagproperty of the senderargument to index into an array of NSStringobjects. (For the first button, the tagwould be 0, while the second would be 1, etc.)

如果我正在设计这个类,我会使用一种操作方法并使用参数的tag属性sender来索引NSString对象数组。(对于第一个按钮,tag将是0,而第二个将是1,等等)

You should rename your UIImageViewivar to imageViewto reduce ambiguity.

您应该将您的UIImageViewivar重命名为imageView以减少歧义。

@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