UICollectionView将手指拖过单元格以选择它们

使用UICollectionView ,是否可以通过将手指拖过几个单元格来选择多个单元格? 例如,如果您将手指拖过6行,然后向下拖动到下一行,它将选择所有这些。

尝试过简单的事情:

 UISwipeGestureRecognizer *swipeGuesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)]; [self.collectionView addGestureRecognizer:swipeGuesture]; 

但这似乎只是在触及的第一个细胞上调用该方法。

有任何想法吗?

您可以使用UIPanGestureRecognizer。 并根据平移事件的位置,跟踪通过的细胞。 当手势结束时,您将拥有一系列选定的单元格。

确保cancelsTouchesInView设置为NO 。 您需要使用gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:设置委托gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:gestureRecognizerShouldBegin实现以确保CollectionView仍然可以滚动

Swift 3:滑动以选择自动滚动和工作滚动。

 var selectMode = false var lastSelectedCell = IndexPath() func setupCollectionView() { collectionView.canCancelContentTouches = false collectionView.allowsMultipleSelection = true let longpressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongpress)) longpressGesture.minimumPressDuration = 0.15 longpressGesture.delaysTouchesBegan = true longpressGesture.delegate = self collectionView.addGestureRecognizer(longpressGesture) let panGesture = UIPanGestureRecognizer(target: self, action: #selector(didPan(toSelectCells:))) panGesture.delegate = self collectionView.addGestureRecognizer(panGesture) } func selectCell(_ indexPath: IndexPath, selected: Bool) { if let cell = collectionView.cellForItem(at: indexPath) { if cell.isSelected { collectionView.deselectItem(at: indexPath, animated: true) collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.centeredVertically, animated: true) } else { collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredVertically) } if let numberOfSelections = collectionView.indexPathsForSelectedItems?.count { title = "\(numberOfSelections) items selected" } } } func didPan(toSelectCells panGesture: UIPanGestureRecognizer) { if !selectMode { collectionView?.isScrollEnabled = true return } else { if panGesture.state == .began { collectionView?.isUserInteractionEnabled = false collectionView?.isScrollEnabled = false } else if panGesture.state == .changed { let location: CGPoint = panGesture.location(in: collectionView) if let indexPath: IndexPath = collectionView?.indexPathForItem(at: location) { if indexPath != lastSelectedCell { self.selectCell(indexPath, selected: true) lastSelectedCell = indexPath } } } else if panGesture.state == .ended { collectionView?.isScrollEnabled = true collectionView?.isUserInteractionEnabled = true swipeSelect = false } } } func didLongpress() { swipeSelect = true }