swift - Swift 集合视图选择
问题描述
我有一个照片集视图,如何限制用户选择的照片数量。例如,用户可以在收藏视图中选择最多 3 张照片
解决方案
这唤醒了我。我已经构建了两种方法,一种用于handleMultipleCellSelection
检查最大选定项目数,另一种用于handleCellSelection
.
这个方法 被handleMultipleCellSelection
调用 didSelectItemAt
UICollectionViewDelegate
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)
}
推荐阅读
- python - 如何在 SymPy 中使用 nonlinsolve 返回有限(浮点)值?
- typescript - 如何在没有冲突的情况下将 Mocha 和 Jest 与 TypeScript 一起使用?
- amazon-web-services - 在 AWS Lambda 中运行 selenium 测试 (chrome) - NET Core
- angular7 - 如何修改从 observable 获取的数据?
- ansible - 如何避免类型转换警告?
- android - Gradle + Cmake 在连接路径时添加意外的引号
- postgresql - Postgres:行级安全性不适用于视图
- websphere - 在非联合环境中增加极端规模的命令是什么
- c# - 从 RDL 调用 Web api 时获取“System.Security.SecurityException”
- javascript - 如何通过单击快速按钮将用户重定向到同一域上的不同路径?