首页 > 解决方案 > Swift 集合视图选择

问题描述

我有一个照片集视图,如何限制用户选择的照片数量。例如,用户可以在收藏视图中选择最多 3 张照片

标签: swiftuicollectionview

解决方案


这唤醒了我。我已经构建了两种方法,一种用于handleMultipleCellSelection检查最大选定项目数,另一种用于handleCellSelection.

这个方法 被handleMultipleCellSelection 调用 didSelectItemAtUICollectionViewDelegate

var selectedServicesId = NSMutableArray()

  func handleMultipleCellSelection(_ cell: UICollectionViewCell, indexPath: IndexPath){
        if self.selectedServicesId.count < 3 {
            self.handleCellSelection(cell, indexPath: indexPath)
        }else{
            if  self.selectedServicesId.contains(servicesData!.data[indexPath.row].id){
                handleCellSelection(cell, indexPath: indexPath)
            }else{

                let alert = UIAlertController(title: "Attention", message: "You can not select more than three items", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        }
    }

func handleCellSelection(_ cell: UICollectionViewCell, indexPath: IndexPath){
    if cell.backgroundColor == UIColor.white{

        cell.backgroundColor = UIColor(hexString: "#FFB74D")
        self.selectedServicesId.add(servicesData!.data[indexPath.row].id)
        self.searchView.alpha = 1
    }else{
        cell.backgroundColor = UIColor.white
        self.selectedServicesId.remove(servicesData!.data[indexPath.row].id)
        if selectedServicesId.count == 0{
            self.searchView.alpha = 0
        }
    }
}
}

在你的didSelectItemAt

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell : UICollectionViewCell = collectionView.cellForItem(at: indexPath) as! CategoryCollectionViewCell
        handleMultipleCellSelection(cell, indexPath: indexPath)
    }

推荐阅读