删除以编程方式添加的 UIImageView [英] Remove programmatically added UIImageView

查看:17
本文介绍了删除以编程方式添加的 UIImageView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个游戏,通过单击按钮生成一张扑克牌.我正在使用此代码来执行此操作:

I am creating a game that generates a playing card on a button click. I'm using this code to do this:

var imageView = UIImageView(frame: CGRectMake(CGFloat(pos), 178, 117, 172));
    var image = UIImage(named: "\(deck[Int(card)])_of_\(suits[Int(arc4random_uniform(4))])")
    imageView.image = image
    self.view.addSubview(imageView)

但我还有另一个按钮可以重置游戏.我希望能够仅删除以编程方式添加的卡片.对此的任何帮助将不胜感激.

But I have another button that resets the game. I want to be able to remove only the cards added programatically. Any help on this will be appreciated.

推荐答案

您可以在某些属性中跟踪 imageView,当您想删除它时,您只需:

You can keep track of that imageView in some property, and when you want to remove it you simply:

imageView.removeFromSuperview()  // this removes it from your view hierarchy 
imageView = nil;                 // if your reference to it was a strong reference, make sure to `nil` that strong reference

<小时>

顺便说一句,您可能知道,UIImage(named:...) 会将图像缓存在内存中.如果你想要,很好,但如果不是,你可能想要使用 UIImage(contentsOfFile:...) 和该资源的完全限定路径.如果您使用 UIImage(named:...),即使 UIImageView 已被删除,图像仍将保留在内存中.正如文档所说:


BTW, as you may know, UIImage(named:...) will cache the images in memory. If you want that, fine, but if not, you might want to use UIImage(contentsOfFile:...) with the fully qualified path to that resource. If you use UIImage(named:...), the image will stay in memory even after the UIImageView has been removed. As the documentation says:

如果您有一个只显示一次的图像文件,并希望确保它不会被添加到系统缓存中,您应该使用 imageWithContentsOfFile: 创建图像.这将使您的一次性图片远离系统图片缓存,从而有可能改善您应用的内存使用特性.

If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.

这篇关于删除以编程方式添加的 UIImageView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆