【问题标题】:How can call selectItemAt: function at collectionView(_:didSelectItemAt:)?如何在 collectionView(_:didSelectItemAt:) 处调用 selectItemAt: 函数?
【发布时间】:2019-11-26 08:00:16
【问题描述】:

我有一个 UICollectionView,并且 collecitonView 有足够的项目。
当通过触摸选择第 5 个单元格时,我想取消第 5 个单元格选择并返回上一个选择的单元格。
UICollectionView 具有以下选项。

var lastSelectedIndexPath: IndexPath
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.allowsMultipleSelection = false
collectionView.allowsSelection = true

...

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if shouldRollBackSelection {
        // just test code
        collectionView.selectItem(at: lastSelectedIndexPath, animated: false, scrollPosition: UICollectionView.ScrollPosition())
    } else {
        lastSelectedIndexPath = indexPath
    }
}

如果collectionView.selectItem(...)函数被调用,最后选中单元格的isSelected属性的didSet会被调用两次。
第一次调用为假对真,第二次调用为真对假。结果,最后选中的单元格的 isSelected 属性为 false。

我想回滚 UICollectionView 的 Cell 的选择。我的意思是我不允许选择特定的单元格。

【问题讨论】:

  • 那么您现在面临的挑战是什么?
  • 我没有得到您的问题,您想要执行什么特定功能?
  • @Abhishek 我编辑了这个问题。这是最后一行。
  • @KarthickRamesh 哦,对不起。挑战是最后一行。我加了。
  • 所以基本上,假设 UICollectionView 中有 8 个单元格。那么您需要用户不应该选择第 4 和第 8 单元格之类的东西吗?

标签: ios swift uicollectionview


【解决方案1】:

为那些您不想选择的单元格禁用用户交互

 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    if indexPath.row == 4 {
        cell.isUserInteractionEnabled = false
    }
    return cell

  }

【讨论】:

    【解决方案2】:

    这不是最好的方法,但您可以在设置最后一个索引之前添加 guard 以防止重复调用:

    guard lastSelectedIndexPath != indexPath else { return }
    

    【讨论】:

    • 我认为重复调用无关紧要。我编辑了我的问题。
    【解决方案3】:

    最好在 cellForItemAt 重载中停用对单元格的选择:

         func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCel", for: indexPath) as! UpperCollectionViewCell
            if indexPath.row == 4 {
               cell.isUserInteractionEnabled = false
            }
            return cell
        }
    

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多