我得到了照片的 Collection View ,如何限制用户选择的照片数量。例如用户最多可以在收藏 View 中选择 3 张照片
最佳答案
这唤醒了我。我已经构建了两种方法,一种用于 handleMultipleCellSelection
检查最大选定项目数,另一种用于 handleCellSelection
。
此方法handleMultipleCellSelection
在UICollectionViewDelegate
的didSelectItemAt
中调用
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)
}
关于Swift Collection View 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54604731/