简体   繁体   English

如何在iOS应用程序内更改UIImageView中的图像?

[英]How to change the image within a UIImageView inside an iOS app?

I have a UIImageView object that I instantiate and turn into a property inside my iOS app. 我有一个UIImageView对象,我实例化并变成我的iOS应用程序内的属性。 I initialize the attributes for this UIImageView object inside my viewDidLoad method, however, I need to change the image that is contained inside the UIImageView object later on in another method. 我在viewDidLoad方法中初始化此UIImageView对象的属性,但是,我需要稍后在另一个方法中更改UIImageView对象中包含的图像。 When I do this, I for some reason am simply superimposing the new image over top of the old one. 当我这样做时,我出于某种原因只是将新图像叠加在旧图像的顶部。 What I would like to do is simply resize the frame, and replace the old image with the new one. 我想做的只是调整框架的大小,并用新的图像替换旧图像。

Here is the relevant code: 这是相关代码:

Inside my viewDidLoad method: 在我的viewDidLoad方法中:

imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 250, 300, 200)];
imageView.image = [UIImage imageNamed:@"firstImage.png"];
[self.view addSubview:imageView];

and inside my method where I wish to make the changes: 在我希望进行更改的方法中:

imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 250, 200, 300)];
imageView.image = [UIImage imageNamed:@"secondImage.png"];
[self.view addSubview:imageView];

Please bear in mind that I don't want to just change the image, but also the frame size to accommodate the new image. 请记住,我不想仅仅更改图像,还要更改框架大小以适应新图像。 Can anyone see what I am doing wrong? 谁能看到我做错了什么?

You are creating another instance of imageview. 您正在创建另一个imageview实例。 You need to access the same object and change frame and image there. 您需要访问同一个对象并在那里更改框架和图像。

Try this, 尝试这个,

Create imageView as property in the class as, 在类中创建imageView作为属性,

In .h file, 在.h文件中

@property(nonatomic, retain) UIImageView *imageView;

Then in viewDidLoad , 然后在viewDidLoad

self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 250, 300, 200)];
self.imageView.image = [UIImage imageNamed:@"firstImage.png"];
[self.view addSubview:imageView];

The in second method, just change the frame and image as shown below, 在第二种方法中,只需更改框架和图像,如下所示,

self.imageView.frame = CGRectMake(10, 250, 200, 300);
self.imageView.image = [UIImage imageNamed:@"secondImage.png"];

As per you code, you were creating separate instances for imageViews and adding as subviews which will cause it to superimpose on another one. 根据您的代码,您正在为imageView创建单独的实例,并添加为子视图,这将导致它叠加在另一个上。 Instead you need to create a single instance as shown above and modify its frame and image properties whenever required. 相反,您需要创建一个如上所示的实例,并在需要时修改其框架和图像属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM