繁体   English   中英

如何防止collectionView:didSelectItemAtIndexPath委托方法多次调用

[英]How to prevent collectionView:didSelectItemAtIndexPath delegate method called more than once

当我多次单击UICollectionView的单元格两次(双击,三次)时,它的委托方法didSelectItemAtIndexPath也被多次调用。 防止这种危险的最明智的方法是什么?

我将不胜感激。

您可以使用模型对象在其中保留选定的属性(或仅出于此目的可以创建布尔数组)。 并在shouldSelectItemAtIndexPath方法中检查它。

@cihangirs代码:

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath { 
    if (someModel.isSelected) { 
        return NO; 
    } else { 
        someModel.isSelected = YES; 
        return YES; 
    } 
}

这是实现目标的最安全方法:

 (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
  if([[collectionView indexPathsForSelectedItems] containsObject:indexPath]) // checking whether cell is already selected or not
    {
      return;
    }
 else
   {
 // do whatever you want to do on selection of cell

   }
}

这里发生的事情是,每当您选择一个单元格时,它都会自动存储在Collection视图的“ indexPathsForSelectedItems”中,因此,下次您再次点击所选单元格时,此方法[[collectionView indexPathsForSelectedItems] containsObject:indexPath]将检查该单元格是否为是否已选择,如果是,则它将返回该方法,以便不再进行任何操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM