Swift Collection View 选择

标签 swift uicollectionview

我得到了照片的 Collection View ,如何限制用户选择的照片数量。例如用户最多可以在收藏 View 中选择 3 张照片

最佳答案

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

此方法handleMultipleCellSelectionUICollectionViewDelegatedidSelectItemAt中调用

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/

相关文章:

Swift 3 和 EKEventStoreRequestAccessCompletionHandler 抛出异常

Swift 4 - 将数据传递到 Collection View 单元中嵌入的 TableView

ios - 返回部分的标题 View ,但不返回其他部分的标题 View

swift - 如何通过自动布局设置 Collection View 的单元格大小

ios - 在 iOS 中显示来自 pdf 数据的 PDF

ios - 如何重构此代码,以便在Swift中变量之间仅共享某些属性

ios - 如何使用 Photos Framework 仅获取相机胶卷中的图像

ios - 使用核心数据从文本字段中保存和检索数据

ios - UICollectionView insertItemAtIndexPath 不工作

ios - 单击 Collection View 中的单元格即可转换到 View Controller