【问题标题】:Swift 4 - deselect collection view cell if already selectedSwift 4 - 如果已选择,请取消选择集合视图单元格
【发布时间】:2018-02-05 17:54:16
【问题描述】:

我有一个集合视图,用户可以在其中选择多个单元格并将索引数组发送到服务器以保存他们的选择。

一切正常,除了在创建集合视图时需要单击所选项目两次才能取消选择它们。

如何解决双击的问题?

extension ThirdViewController: UICollectionViewDelegate, UICollectionViewDataSource {


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return categoryList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! UserCategoryCollectionViewCell

        cell.categoryLbl.text = categoryList[indexPath.row]

        if Defaults.hasKey(.categoryListIndices) {
            if (Defaults[.categoryListIndices]?.contains(indexPath.row))! {
                cell.alpha = 0.1
                cell.isSelected = true
            } else {

                cell.alpha = 1

            }
        }

        return cell
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! UserCategoryCollectionViewCell


        cell.alpha = 0.1

    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let deselectedCell = collectionView.cellForItem(at: indexPath) as? UserCategoryCollectionViewCell
        deselectedCell?.alpha = 1

        print(deselectedCell?.isSelected)
        collectionView.deselectItem(at: indexPath, animated: false)
    }

}

【问题讨论】:

  • 您必须将UITapGestureRecognizersetNumberOfTapsRequired = 2 设置为单元格以进行双击事件。

标签: ios xcode uicollectionview uicollectionviewcell swift4


【解决方案1】:

首先。将此添加到您的 viewDidLoad。

 collectionView?.allowsMultipleSelection = true

然后添加这两个函数。

 override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell=collectionView.cellForItem(at: indexPath)
    collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [])
    cell?.backgroundColor = Color.hexStringToUIColor(hex: "#F5A331")
    let lbl = cell?.subviews[1] as! UILabel
    lbl.textColor = Style.cellHighlightedColor
}
 override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    collectionView.deselectItem(at: indexPath, animated: true)
    let cell=collectionView.cellForItem(at: indexPath)
    collectionView.deselectItem(at: indexPath, animated: true)
    
    cell?.backgroundColor = UIColor.white
    let lbl = cell?.subviews[1] as! UILabel
    lbl.textColor = UIColor.darkGray
}

这样就可以了

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2016-03-31
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多