How do I clear images from my UIImageView

uiimageview scale image to fit frame
set uiimage to nil swift
'nil' cannot be assigned to type 'uiimage'
swift remove image programmatically
uiimage(named swift)
empty uiimage
uiimageview set image swift 4
get image name from uiimage swift

I have the following code for a compositionalLayout in Swift, but my images are not going away with the reuse of cells.

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet var collectionView: UICollectionView!

    let myInset: CGFloat = 4.0

    let dataColors = [UIColor.red, UIColor.blue, UIColor.green, UIColor.magenta, UIColor.purple, UIColor.orange, UIColor.red, UIColor.blue, UIColor.green, UIColor.magenta, UIColor.purple, UIColor.systemYellow, UIColor.red, UIColor.blue, UIColor.green, UIColor.magenta, UIColor.purple, UIColor.orange, UIColor.red, UIColor.blue, UIColor.green, UIColor.magenta, UIColor.purple, UIColor.systemYellow]

    let theImages = [
            "MEN_8882","002","003","004","005","006","001","002","003","004","005","006",
            "MEN_8882","002","003","004","005","006","001","002","003","004","005","006"
    ]


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        collectionView.setCollectionViewLayout(createCustomLayout(), animated: false)
        collectionView.backgroundColor = .white
        self.collectionView.delegate = self
        self.collectionView.dataSource = self

        collectionView.register(QuickCell.self, forCellWithReuseIdentifier: "cellID")
       //configureCollectionView()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1//dataColors.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataColors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as? QuickCell {
            cell.backgroundColor = dataColors[indexPath.row]
            let mySubView = UIImageView()
            mySubView.image = UIImage(named: theImages[indexPath.row])
            cell.addSubview(mySubView)
            mySubView.translatesAutoresizingMaskIntoConstraints =  false
            mySubView.topAnchor.constraint(equalTo: cell.topAnchor, constant: myInset).isActive = true
            mySubView.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: myInset).isActive = true
            mySubView.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: myInset * (-1)).isActive = true
            mySubView.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: myInset * (-1)).isActive = true
            mySubView.clipsToBounds = true
           // mySubView.layer.cornerRadius = 8
            mySubView.contentMode = .scaleAspectFit
            cell.clipsToBounds = true
            cell.layoutIfNeeded()
            //cell.layer.cornerRadius = 12
            return cell
        } else {
            return UICollectionViewCell()
        }

    }

    func createCustomLayout() -> UICollectionViewLayout {

            let layout = UICollectionViewCompositionalLayout { (section: Int, environment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in

                let myItemInset: CGFloat = 2.0

                let leadingItem = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)))
                leadingItem.contentInsets = NSDirectionalEdgeInsets(top: myItemInset, leading: myItemInset, bottom: myItemInset, trailing: myItemInset)

                let leadingGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.7), heightDimension: .fractionalHeight(1.0))
                let leadingGroup = NSCollectionLayoutGroup.vertical(layoutSize: leadingGroupSize, subitem: leadingItem, count: 1)

                let trailingGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.3), heightDimension: .fractionalHeight(1.0))
                let trailingGroup = NSCollectionLayoutGroup.vertical(layoutSize: trailingGroupSize, subitem: leadingItem, count: 5)

                let fullGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
                let fullGroup = NSCollectionLayoutGroup.horizontal(layoutSize: fullGroupSize, subitems: [leadingGroup, trailingGroup])

                let section = NSCollectionLayoutSection(group: fullGroup)

                section.orthogonalScrollingBehavior = .groupPagingCentered
                section.contentInsets = NSDirectionalEdgeInsets(top: 20, leading: 0, bottom: 20, trailing: 0)

                return section
            }
            return layout
        }

}

The image "MEN..." is portrait while the rest are landscape, and as i scroll back and forth, i see overlapping images in the items.

the code for QuickCell is empty - I'm not sure what to put ther, some kind of initalization? But it should work anyways, right?

import UIKit

class QuickCell: UICollectionViewCell {
}

To remove image from UIImageView do the following.

yourImageView.image = nil 

How to clear memory after UIImageV…, when appending images to the array); a UIImageView; a button which sets the imageView.animationImages = arrayOfImages and calls imageView. startAnimating� After setting the image, call the sizeToFit () method to recompute the image view’s size based on the new image and the active constraints. This property is set to the image you specified at initialization time.

The problem here is that you are adding a new UIImageView every time the cell is reused. The ones added in previous interations of the cellForItemAtIndexPath: method do not go away, so others are added on top.

These are the problem lines:

let mySubView = UIImageView()
mySubView.image = UIImage(named: theImages[indexPath.row])
cell.addSubview(mySubView)

It would be better to add the image view once when a cell is initialised (or in storyboard with an outlet) then just set the image in the cellForItemAtIndexPath: method.

UIImage, You use image objects to represent image data of all kinds, and the UIImage class is capable of managing data for all image Assign an image to a UIImageView object to display the image in your interface. class var remove: UIImage. The� For images outside of your app’s bundle, use the image With Contents Of File: method. Do not use image views for custom drawing. The UIImage View class does not draw its content using the draw(_:) method. Use image views only to present images. To do custom drawing involving images, subclass UIView directly and draw your image there

You keep adding subviews inside cellForItemAt and this causes the overlapping as cells are dequeued , you need to create an outlet for the imageview or create it programmatically inside the cell like

class QuickCell: UICollectionViewCell {


    let mySubView = UIImageView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        let myInset: CGFloat = 4.0
        self.contentView.addSubview(mySubView)
        mySubView.translatesAutoresizingMaskIntoConstraints =  false
        mySubView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: myInset).isActive = true
        mySubView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: myInset).isActive = true
        mySubView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: myInset * (-1)).isActive = true
        mySubView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: myInset * (-1)).isActive = true
        mySubView.clipsToBounds = true
       // mySubView.layer.cornerRadius = 8
        mySubView.contentMode = .scaleAspectFit

    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}

With

cell.mySubView.image = UIImage(named: theImages[indexPath.row])

or

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as? QuickCell {
        cell.subviews.forEach { 
             if $0.tag == 333 {
               $0.removeFromSuperview()
             }
         }
        cell.backgroundColor = dataColors[indexPath.row]
        let mySubView = UIImageView()
        mySubView.tag = 333

Reset a UIImageView in Swift, Reset a UIImageView in Swift. How do you implement swift code that deletes a image from or clears a uiimageview? imageView.image = nil. Posting to the forum is only allowed for members with active accounts. Clear Recently Used Background Images by Editing the Registry Manually. If you’ve accidentally added an image as a background and want to get rid of it, you can’t simply right-click the image and delete it. Sure, you could add five more different images, but using this Registry edit is a lot easier to do.

A subview of type UIImageView is added to your custom Cell (QuickCell) each time your collection view cell is resued. It happens in cellForRowAt delegate method.

So, you have to remove previously added image views from your cell first before adding a new one.

I suggest you move your cell configuration code to QuickCell.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
    if let quickCell = quickCell as? QuickCell {
        quickCell.backgroundColor = self.dataColors[indexPath.row]
        quickCell.setImage(self.theImages[indexPath.row], insetBy: self.myInset)
        return quickCell
    }
    return cell
}

Do your custom cell configurations here!

class QuickCell: UICollectionViewCell {
    func setImage(_ image: UIImage, insetBy inset: CGFloat) {
        // Remove previously added image views first if any
        for subview in self.subviews where subview.isKind(of: UIImageView.self) {
            subview.removeFromSuperview()
        }
        let imageView = UIImageView()
        imageView.image = image
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFit
        self.addSubview(imageView)

        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
            imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: inset),
            imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: inset * (-1)),
            imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: inset * (-1))
        ])
        self.layoutIfNeeded()
    }
}

Programming IOS 11: Dive Deep Into Views, View Controllers, and , With a UIImage Create a UIImage wrapping the final CIImage by calling we see just the clear color, with a gradation in between, so that the image fades away� This library provides an async image downloader with cache support. For convenience, we added categories for UI elements like UIImageView, UIButton, MKAnnotationView. Features. Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management; An asynchronous image downloader

This is checked by default for UICollectionView, try to uncheck it. It should work for you.

Programming iOS 9: Dive Deep into Views, View Controllers, and , You can then draw the UIImage into some graphics context. for blending between the photo of me and a default clear background: where the radial gradient is� This example demonstrates how do I clear an imageview in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml.

Programming IOS 10: Dive Deep Into Views, View Controllers, and , If a CIFilter requires an input image and you already have a CIImage to fulfill to a UIImageView, as its image, and that the UIImageView will render the image. for blending between the photo of me and a default clear background: where the � Questions: I’ve an UIImageView with content mode Aspect Fit of size 220×155. I’m dynamically inserting different images in different resolutions, but all larger than the size of the UIImageView. As the content mode is set to Aspect Fit, the image is scaled with respect to the ratio to fit the UIImageView. My problem is, that

Remove image from the cache � Issue #85 � Alamofire , Hi, I have fetched the image using the below code inside a function in UIImageView extension. self.af_setImageWithURL(url� When I do the same expansion of the image size in my word processor and then clip back to IrfanView, the original image is retained. My only conclusion is that OFFICE 2007 plays around with graphics and it does not seem to make any difference if you clip the image into WORD or import it, WORD still messes around with it.

Cannot remove image from cache � Issue #250 � Alamofire , Here is my URL: http://dev.photonapp.net/App/Images/User/2/ Here is how I'm loading the image into a UIImageView: if let url = URL(string:� The image is scaled, sized to fit or positioned in the UIImageView according to the ContentMode property. If either LeftCapWidth or TopCapHeight are set, the image is stretched according to those values instead. This view is aware of stretchable images created with CreateResizableImage(UIEdgeInsets)

Comments
  • I've tried now a few versions of that, but it still has overlapping images. I inserted the line: mySubView.image = nil just above the line mySubView.image = UIImage(named: theImages[indexPath.row]) ... should it go somewhere else?
  • Thanks. I changed a bit and it works. But I don't undersstand why I cannot link and UIImageView from the StoryBoard and simply change the image? Why do I get a "unwrapped nil" error when the UIImageView is right there? It should be weak or not or what?
  • You can achieve this through Storyboard as well. I've encountered an "unwrapped nil" error when I failed to link an IBOutlet to the storyboard.