在集合视图中单击图像会选择其他图像

问题描述

我有以下代码

import UIKit
import Photos
import PhotosUI

private let reuseIdentifier = "Cell"

class CollectionVC: UICollectionViewController,UICollectionViewDelegateFlowLayout {

    var imageArray = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

     grapPhotos()
       

        
    }


    override func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        
        return imageArray.count
    }

    override func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath as IndexPath)
        let imageView = cell.viewWithTag(1) as! UIImageView
        
        collectionView.allowsMultipleSelection = true
        cell.layer.cornerRadius = 4
        imageView.image = imageArray[indexPath.row]
    
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
        
        if let cell = collectionView.cellForItem(at: indexPath) {
          cell.layer.borderColor = #colorLiteral(red: 0.1411764771,green: 0.3960784376,blue: 0.5647059083,alpha: 1)
          cell.layer.borderWidth = 5
        
        }
        
        
    }
    
    override func collectionView(_ collectionView: UICollectionView,diddeselectItemAt indexPath: IndexPath) {
        if let cell = collectionView.cellForItem(at: indexPath) {
          cell.layer.borderColor = #colorLiteral(red: 0.1411764771,alpha: 1)
          cell.layer.borderWidth = 0
        }
    }
    
    func grapPhotos() {
        
        let imgManager = PHImageManager.default()
        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = true
        requestOptions.deliveryMode = .highQualityFormat
        
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
        fetchOptions.predicate = nspredicate(format: "mediaType = %d || mediaType = %d",PHAssetMediaType.image.rawValue,PHAssetMediaType.video.rawValue)
        
        if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: fetchOptions) {
            
            if fetchResult.count > 0 {
                
                for i in 0..<fetchResult.count {
                    imgManager.requestimage(for: fetchResult.object(at: i),targetSize: CGSize(width: 200,height: 200),contentMode: .aspectFill,options: requestOptions,resultHandler: {
                        
                        image,error in
                        
                        self.imageArray.append(image!)
                        
                        
                    })
        
                    
                }
            }
            else {
                self.collectionView?.reloadData()
                print("No Photos")
            }
        }
    }
    func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeforItemAt indexPath: IndexPath) -> CGSize {
        
        let width = collectionView.frame.width / 3 - 6
        
        
        
        return CGSize(width: width,height: width)
    }

    func collectionView(_ collectionView: UICollectionView,minimumLinespacingForSectionAt section: Int) -> CGFloat {
        
        return 6.0
    }
    func collectionView(_ collectionView: UICollectionView,minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        
        return 6.0
    }

}

很抱歉,但是我真的不知道我要去哪里错。这是我所有的CollectionViewController代码,然后在情节提要中有一个集合VC,在一个单元格中有一个图像,图像的标签为1,然后在一个单元格中,标识符为"Cell"。我遇到的问题是,当我在手机上运行代码时,选择一个图像最终会选择其他图像。例如:我选择第一个图像,然后向下滚动并选择另一个图像。我做了一点测试,前21张图像几乎是唯一的。但是就好像图像几乎具有相同的id。就像选择第一个图像一样,也会选择第22个图像。顺便说一下,我正在构建一个自定义图像选择器。

解决方法

这里有多个问题,但是您抱怨的主要问题是因为您忘记了单元的重用。您需要在cellForItem中配置单元,而不是在didSelectdidDeselect中进行配置。

当您的didSelect转身并直接与物理单元对话时,这完全是在做错误的事情。相反,didSelectdidDeselect应该与您的数据模型对话,并在模型的对象中设置一些属性,这些属性表示这些索引路径上的对象应该被视为已选中,而在其他索引路径处的对象则不应被选择。然后重新加载数据。

然后,cellForItem出现时,它必须根据数据模型和索引路径完全配置其单元格 ,以显示其选择的外观还是未选择的外观。这样,如果某个单元格在先前选择的行中,但现在在未选择的行中被重用,则它具有所需的未选择的外观。

换句话说,只有cellForItem应该根据单元格进行思考。其他所有人都应该仅根据索引路径来考虑(或者甚至更好地根据与数据相关联的某些唯一标识符来考虑,但这是另一回事了。)