【问题标题】:why selected cell in collection view doesn't show correctly in the UICollection View Swift 3?为什么集合视图中的选定单元格在 UICollection View Swift 3 中无法正确显示?
【发布时间】:2017-11-05 06:05:44
【问题描述】:

我正在使用 swift 3,我的应用中有收藏视图,其中显示 iPhone 画廊。一切都很好但我希望用户可以选择一些照片,这可能会发生但问题是我在每个单元格中使用了另一个小图像,当用户选择该单元格时,图片将显示一个用户可以理解该单元格的勾号已被选中 - 这将在开始时起作用,但是当用户滚动集合视图时,一些用户没有选择它们的单元格也有这个勾号! **请记住,选择和取消选择运行良好,问题只是为了显示这个勾** **我在单元格中有带有标签的图像,当用户选择单元格或没有选择该单元格时,该图像将显示一个勾号或不显示**

我知道这些代码比你想象的要多,但是很多人需要访问所有代码,所以你可以在下面看到我的代码

 import UIKit
 import Photos
 class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
let arr_img = NSMutableArray()

@IBOutlet var collview: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    let allPhotosOptions : PHFetchOptions = PHFetchOptions.init()
    allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
    let allPhotosResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)
    allPhotosResult.enumerateObjects({ (asset, idx, stop) in

        self.arr_img.add(asset)
    })

}
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
    let retinaScale = UIScreen.main.scale
    let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//CGSizeMake(size * retinaScale, size * retinaScale)
    let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
    let square = CGRect(x: 0, y: 0, width: cropSizeLength, height: cropSizeLength)//CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength))
    let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))

    let manager = PHImageManager.default()
    let options = PHImageRequestOptions()
    var thumbnail = UIImage()

    options.isSynchronous = true
    options.deliveryMode = .highQualityFormat
    options.resizeMode = .exact
    options.normalizedCropRect = cropRect

    manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
        thumbnail = result!
    })
    return thumbnail
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK:
//MARK: Collectioview methods
func collectionView(_ collectionView: UICollectionView,
                    numberOfItemsInSection section: Int) -> Int {
    return arr_img.count
}
func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                  for: indexPath)
    let imgview : UIImageView = cell.viewWithTag(20) as! UIImageView
    imgview.image = self.getAssetThumbnail(asset: self.arr_img.object(at: indexPath.row) as! PHAsset, size: 150)

    return cell
}

}

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
 let cell = collectionView.cellForItem(at: indexPath as IndexPath)
    if cell!.isSelected == true {


        print(indexPath)
        cell?.backgroundColor = UIColor.orange
        print("Cell is Selected!")
        let selectView : UIImageView = cell?.viewWithTag(22) as! UIImageView
        selectView.image = UIImage(named: "Select.png")
    }

    else if cell!.isSelected != true        {

        collectionView.cellForItem(at: indexPath as IndexPath)

    cell?.backgroundColor = UIColor.clear
        let selectView : UIImageView = cell?.viewWithTag(22) as! UIImageView
        selectView.image = nil

        print("Cell is  Not Selected!")

    }

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath as IndexPath)

    print(indexPath)
    if cell?.isSelected == true {
        cell?.backgroundColor = UIColor.orange
        print("Cell is Selected In Deselect!")
        let selectView : UIImageView = cell!.viewWithTag(22) as! UIImageView
        selectView.image = nil
        collectionView.cellForItem(at: indexPath as IndexPath)

    }
    else if cell?.isSelected != true        {
        cell?.backgroundColor = UIColor.clear
        collectionView.cellForItem(at: indexPath as IndexPath)

        print("Cell is DeSelected!")
        let selectView : UIImageView = cell!.viewWithTag(22) as! UIImageView
        selectView.image = nil


    }

}

【问题讨论】:

  • 单元格像表格视图单元格一样被重用。您需要维护一个已检查单元格的数组,并在单元格出列后设置刻度图像。
  • 为什么要写 didDeselectItemAt ?因为您的代码仅适用于 didSelect。
  • 细胞被重复使用。在模型中添加属性isSelected,在didSelect/didDeselect 中更新它,并根据cellForItem 中的属性设置刻度。
  • 或者您可以在 didSelect 方法中将 indxPath 添加到数组中。并在 cellForRowAtIndexPath 中检查。
  • @RoboticCat 和 KKRocks:声明额外的数组是个坏建议。该信息应该包含在数据模型中。

标签: ios swift3 uicollectionview uicollectionviewcell selectedindex


【解决方案1】:

只需在您的单元格中点击一个按钮并为其添加标签。

获取数组并执行以下操作。

let arr_selected = NSMutableArray()

func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                      for: indexPath)

        let btn_check : UIButton = cell.viewWithTag(30) as! UIButton
        if arr_selected.contains(indexPath.row){
            btn_check.isSelected = true
        }else{
            btn_check.isSelected = false
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if arr_selected.contains(indexPath.row){
            arr_selected.remove(indexPath.row)
        }else{
            arr_selected.add(indexPath.row)
        }
        self.collview.reloadData()
    }

如果你想要demo,可以从HERE下载

【讨论】:

  • 如何将图像用于选中或取消选中的按钮?
  • 好的,您想使用图像,然后使用图像视图代替按钮,因此当此条件 arr_selected.contains(indexPath.row) == true 更改您的图像视图为选中时,取消选择 @SaeedRahmatolahi
  • 这是我的荣幸。 @SaeedRahmatolahi
  • 它成功了 再问一个问题,如何将选定的图像存储到数组中?
  • 您已经将选定的图像存储到 arr_selected 的数组中。只需 print("(arr_selected)") 您将获得所有选定图像的索引路径。
猜你喜欢
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多