【问题标题】:CollectionView didDeselectItemAt not getting called for Single selection in CollectionViewCollectionView didDeselectItemAt 没有被调用 CollectionView 中的单选
【发布时间】:2020-04-16 08:17:04
【问题描述】:

以下是我的 CollectionView 代码

    categoryCollectionView.delegate = self
    categoryCollectionView.dataSource = self
    categoryCollectionView.allowsSelection = true
    categoryCollectionView.allowsMultipleSelection = false

以下是 UICollectionViewCell 代码

class AppPageCategoryViewCell: UICollectionViewCell {
var catgory : String?

@IBOutlet weak var titleLbl: UILabel!

@IBOutlet weak var closeImageView: UIImageView!



@IBOutlet weak var stackContainer: UIView!
var facet : Facets?

func setUI() {
    titleLbl.text = facet?.name ?? ""
    let isSelected = facet?.isSelected ?? false
    stackContainer.layer.borderColor =  UIColor.black.cgColor
    stackContainer.backgroundColor = isSelected ? UIColor.black : UIColor.white
    titleLbl.textColor = isSelected ? UIColor.white : UIColor.black
    closeImageView.image = closeImageView.image?.withRenderingMode(.alwaysTemplate)
    closeImageView.tintColor = UIColor.hexStringToUIColor(hex: AppStrings.whiteColor)
    stackContainer.layer.cornerRadius =  16
    stackContainer.layer.borderWidth = 1
    closeImageView.isHidden = !isSelected

  }
}

以下是选择取消选择方法

 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

    print("deselect----------deselect")

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

     print("select----------select")

}

现在 didDeselectItemAt 不会被调用,如果我选择一个项目并选择另一个项目,或者如果我选择相同的项目 didDeselectItemAt 根本不会被调用,它只是在调用 didSelectItemAt 方法为什么?如何解决这个问题?

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell


    【解决方案1】:

    此委托方法未触发,因为您将布尔值“allowsMultipleSelection”设置为 false。必须为 true 才能允许取消选择该项目。

    https://developer.apple.com/documentation/uikit/uitableview/1614938-allowsmultipleselection

    编辑:

    我相信你需要做的是使用collectionView的委托方法“shouldSelectItemAt”来检查被点击的单元格是否已经被选中。如果为true,则可以取消选择它,如果为false,则什么也不做。

    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        if let currentIndexPathSelected = cellSelectedIndexPath, currentIndexPathSelected == indexPath {
            collectionView.deselectItem(at: indexPath, animated: true)
            collectionView.delegate?.collectionView?(collectionView, didDeselectItemAt: indexPath)
            return false
        }
        return true
    }
    

    cellSelectedIndexPath 是一个私有变量,用于保存当前选定的 indexPath。

    调用委托将触发 didDeselectItemAt 方法。

    如果有帮助,请告诉我。

    【讨论】:

    • 您可能想尝试使用委托方法“collectionView(_:shouldSelectItemAt:)”,如果已经选择了一个单元格,则返回 false,否则返回 true。如果点击的单元格是选中的单元格,您也可以返回 true,这将取消选择它。
    猜你喜欢
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多