Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove programmatically added 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.

like image 308
Lee Price Avatar asked Oct 26 '14 02:10

Lee Price


1 Answers

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

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:

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.

like image 180
Rob Avatar answered Oct 16 '22 17:10

Rob