如何从UIImageView清除图像

我在Swift中有以下用于compositionalLayout的代码,但是我的图像并没有随着单元的重用而消失。

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.systemYellow,UIColor.systemYellow]

    let theImages = [
            "MEN_8882","002","003","004","005","006","001","MEN_8882","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,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
        }

}

图像“ MEN ...”是人像,其余的是风景,当我前后滚动时,我看到物品中有重叠的图像。

QuickCell的代码为空-我不确定该怎么写,某种形式的初始化?但这还是应该可以的,对吧?

import UIKit

class QuickCell: UICollectionViewCell {
}
aabb5888157 回答:如何从UIImageView清除图像

要从image中删除UIImageView,请执行以下操作。

yourImageView.image = nil 
,

您继续在cellForItemAt内添加子视图,这会在单元出队时导致重叠,您需要为imageview创建一个出口在像这样的单元内以编程方式创建它>

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")
    }


}

使用

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

    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
,

这里的问题是,每次重复使用单元格时,您都要添加一个新的UIImageView。在cellForItemAtIndexPath:方法的先前版本中添加的内容不会消失,因此其他内容会添加到顶部。

这些是问题所在:

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

最好在初始化单元格时(或在带有插座的情节提要中)添加一次图像视图,然后在cellForItemAtIndexPath:方法中设置图像。

,

每次检索集合视图单元格时,都会将类型为 UIImageView 的子视图添加到自定义单元格(QuickCell)。它发生在 cellForRowAt 委托方法中。

因此,您必须先从单元格中删除以前添加的图像视图,然后再添加新的视图。

我建议您将单元配置代码移至 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
}

在这里进行自定义单元配置!

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,imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor,constant: inset * (-1)),imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor,constant: inset * (-1))
        ])
        self.layoutIfNeeded()
    }
}
,

Uncheck & try

默认情况下,UICollectionView已选中此选项,请尝试取消选中它。它应该为您工作。

本文链接:https://www.f2er.com/3168080.html

大家都在问