9

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.

jww
  • 97,681
  • 90
  • 411
  • 885
Lee Price
  • 5,182
  • 11
  • 34
  • 36

1 Answers1

11

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.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thanks for this. As you can probably tell, I'm very new to this and this is my first app. I don't want to cache the images so I'm trying to take your advice on using `contentsOfFile` instead. I've looked into this and I think I need something like this... `var path : String? = NSBundle.pathForResource("ace_of_spades", ofType: "png", inDirectory: "Images")` then load the image like this: `var image = UIImage(contentsOfFile: path)` But this is throwing an error. Any advice? – Lee Price Oct 26 '14 at 11:35
  • `pathForResource` is not a class method. It's an instance method. So you have to specify which `NSBundle` instance to use, e.g. `NSBundle.mainBundle().pathForResource(...)`. Whether you use the rendition is `inDirectory` or the one without depends upon where precisely the images are stored in your bundle. (Often they're in the top level of the bundle even though they're listed in a "group" in the project.) I cannot say without seeing the project. – Rob Oct 26 '14 at 13:49