【问题标题】:Previously selected UICollectionViewCells are deselected after non-selectable cell is tapped在点击不可选择的单元格后取消选择以前选择的 UICollectionViewCells
【发布时间】:2014-02-04 23:56:21
【问题描述】:

我正在实现启用多选的 UICollectionView。

我的一些单元格是可选择的,有些则不是。以下是事件链:

  1. 我选择了几个单元格,点击它们并将YES 返回到
    • shouldHighlightItemAtIndexPath:
    • shouldSelectItemAtIndexPath:
  2. 我尝试通过点击来选择一个不可选择的单元格(不可选择的方面是通过将NO 返回到shouldSelectItemAtIndexPath: 来实现的)
  3. 结果:所有选定的单元格都被取消选择,并在它们上调用didDeselectItemAtIndexPath:。注意:shouldDeselectItemAtIndexPath: 不会被调用。

预期结果:什么都没有发生。

这是正常行为吗?我在文档中找不到任何内容。如果是这样,我怎样才能不取消选择我的单元格?

【问题讨论】:

  • 您是否将表格视图的allowsMultipleSelection 设置为YES?
  • 我知道我会得到这个问题...应该提到它...是的我做到了。
  • 尝试实现委托方法tableView:willDeselectRowAtIndexPath:,在里面设置断点,看看什么时候调用。这可能有助于了解正在发生的事情。
  • 我正在使用 UICollectionView,而不是 UITableView。但由于这两个非常相似,我调查了一下。 UICollectionViewDelegate 协议中没有willDoXOrY 方法,但有一个shouldDeselectItemAtIndexPath 方法。我查了一下,没有调用。好主意。
  • @BlackRider 实际上,我确实在帖子的第一行提到了“启用多项选择”。

标签: ios objective-c uikit uicollectionview uicollectionviewcell


【解决方案1】:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeue...

    cell.userInteractionEnabled = isSelectableIndexPath(indexPath)

    return cell
}

func isSelectableIndexPath(indexPath: NSIndexPath) -> Bool {
    //logic to check if cell is selectable
}

这是通过禁用与​​单元格的交互来实现的。

【讨论】:

  • 谢谢...这对我有用,而且比其他回复也好,但不太容易让其他人理解你为什么要这样做
  • 完美的解决方案,tnx 很多。
【解决方案2】:

我不得不面对完全相同的问题,collectionView:shouldDeselectItemAtIndexPath: 没有被调用。如果我点击不可选择的单元格,我的解决方案包括手动重新选择当前选定的单元格:

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL isSelectable = /* decide if currently tapped cell should be selectable */;

    NSIndexPath *selectedItemIndexPath = /* NSIndexPath of the current selected cell in the collection view, set in collectionView:didSelectItemAtIndexPath: */;

    if (!isSelectable) {
        // the cell isn't selectable, we have to reselect the previously selected cell that has lost selection in the meanwhile
        // without reloading first the cell the selection is not working...
        [collectionView reloadItemsAtIndexPaths:@[selectedItemIndexPath]];
        [collectionView selectItemAtIndexPath:selectedItemIndexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    }

    return isSelectable;
}

如果您的收藏视图正在滚动(隐藏当前选定的单元格),请记住重新选择collectionView:cellForItemAtIndexPath: 中的单元格。

我不太喜欢这个解决方案,它太“hacky”,但它确实有效。我希望在collectionView:shouldDeselectItemAtIndexPath: 中执行所有逻辑,但它没有被调用,我不明白为什么。

【讨论】:

    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    相关资源
    最近更新 更多