Delete programmatically added UIImageView

I am creating a game that generates a game card at the click of a button. I use this code for 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 remove only cards added programmatically. Any help on this would be greatly appreciated.

+6
source share
1 answer

You can track this imageView in some property, and if 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 know, UIImage(named:...) will cache images in memory. If you want this, fine, but if not, you can use UIImage(contentsOfFile:...) with the full path to this resource. If you use UIImage(named:...) , the image will remain in memory even after deleting the UIImageView . As the documentation says:

If you have an image file that will be displayed only once, and you want to make sure that it is not added to the system cache, you must create your image using imageWithContentsOfFile: This will save a one-time image from the system cache, which will potentially improve the usage characteristics of your application.

+8
source

Source: https://habr.com/ru/post/977224/


All Articles