【问题标题】:Restricting Cell Selection based on section根据部分限制单元格选择
【发布时间】:2022-02-22 08:43:42
【问题描述】:

我有一个这样的 CollectionView 数据源;

struct HomeSection {
    var title: String?
    var cellType: [HomeCellType]
    
    init(title: String?, cellType: [HomeCellType]) {
        self.title = title
        self.cellType = cellType
    }
}

struct HomeModel {
    static let model = [
        HomeSection(title: "Stock", cellType: [.inStock(text: "Show In-Stock only")]),
        HomeSection(title: "Product", cellType: [.walls(text: "Walls"), .floors(text: "Floors"), .fabrics(text: "Fabrics")]),
        HomeSection(title: "Similarity", cellType: [.similarity]),
        HomeSection(title: "Upload", cellType: [.camera, .photo])
    ]
}

我想限制

HomeSection(title: "Product", cellType: [.walls(text: "Walls"), .floors(text: "Floors"), .fabrics(text: "Fabrics")])

能够选择一个单元格。我已经完成了override var is Selected 方法。但是,一旦我在另一个部分中选择了另一个单元格,它就会取消选择该部分中的单元格。我将如何在didSelectItemForIndexPath 中处理这个问题?

更新

我这样称呼我的数据源;

private let dataSource = HomeViewDataSource(sections: HomeModel.model)

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch dataSource.sections[indexPath.section].cellType[indexPath.item] {
    }
}

【问题讨论】:

    标签: swift model uicollectionview uicollectionviewcell


    【解决方案1】:

    对于限制,您可以使用:

    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool
        if (condition) {
            return false
        } else {
            return true
        }
    }
    

    为了一次有多个选择,您可以使用:

    collectionView.allowsMultipleSelection = true
    

    可选地限制选择:

    shouldSelectdidSelect 中检查是否已经选择了任何不需要的单元格:

    collectionView.indexPathsForSelectedItems
    

    然后根据需要取消选择它们:

    collectionView.deselectItem(at: <#IndexPath#>, animated: <#Bool#>)
    

    【讨论】:

    • 这是一个collectionView
    • 这适用于取消选择问题,但我只希望在该部分中选择 1 个单元格...如何实现?
    • 您的意思是每个部分只有 1 个单元格,但每个 collectionView 有多个单元格?
    • 我有多个部分,其中一个部分包含三个单元格。我只想一次选择这三个单元格中的一个。
    猜你喜欢
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多