尽管滚动,UICollectionView indexPathForItemAtPoint返回相同的项目

使用UICollectionView的indexPathForItemAtPoint的正确语法是什么?

当我滚动它时,我正在使用以下代码来尝试识别位于UICollectionView中心的单元格。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView { //locate the scrollview which is in the centre CGPoint centerPoint = CGPointMake(self.collectionView.frame.size.width / 2, self.collectionView.frame.size.height /2); NSIndexPath *indexPathOfCentralCell = [self.collectionView indexPathForItemAtPoint:centerPoint]; } 

但是,无论我如何滚动,这总是给我相同的indexPath。

我究竟做错了什么?

您正在查找静态单元格中的静态点。 是的,你将永远得到相同的细胞。

为了处理滚动,您需要将scrollview的位置添加到支票中。 像这样的东西:

 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { //locate the scrollview which is in the centre CGPoint centerPoint = CGPointMake(self.collectionView.frame.size.width / 2 + scrollView.contentOffset.x, self.collectionView.frame.size.height /2 + scrollView.contentOffset.y); NSIndexPath *indexPathOfCentralCell = [self.collectionView indexPathForItemAtPoint:centerPoint]; } 

您想要执行此操作的示例是,您希望在UICollectionView上捕获手势,然后对UICollectionView中属于滑动手势位置的特定项执行某些操作。 下面的代码作为UICollectionViewController中的方法将返回正确的单元格,并考虑在集合视图中滚动。

 - (UICollectionViewCell *) cellForGesture:(id)sender { UISwipeGestureRecognizer * gesture = sender; CGPoint point = [gesture locationInView:self.view]; NSLog(@"Swipe location: %f, %f", point.x, point.y, nil); CGPoint pointInCollection = CGPointMake(point.x + self.collectionView.contentOffset.x, point.y + self.collectionView.contentOffset.y); NSIndexPath * indexPath = [self.collectionView indexPathForItemAtPoint:pointInCollection]; UICollectionViewCell * cell = [self.collectionView cellForItemAtIndexPath:indexPath]; return cell; } 

您可以在这样的上下文中调用上面的方法(其中revealSupplementalControls是您的UICollectionViewCell类上的自定义方法):

 - (IBAction) swipeLeft:(id)sender { UICollectionViewCell * cell = [self cellForGesture:sender]; [cell revealSupplementalControls]; } 

如果要使用UILongPressGesture检索特定的UICollectionViewCell,请在Swift中执行此操作

 @IBAction func cellAtLongPress(sender:UILongPressGestureRecognizer) { var location = sender.locationInView(self.view) // adjust the location to account for scrolling location.x += self.collectionView.contentOffset.x location.y += self.collectionView.contentOffset.y let indexPath = self.collectionView.indexPathForItemAtPoint(location) if (indexPath == nil) { print("not over cell") } else { // get the cell where the longPress occured let cell = self.collectionView.cellForItemAtIndexPath(indexPath!)! // you now have the the cell you pressed } } 

Duncan,这是它在Swift中对我有用的东西:

  let location = CGPointMake(self.clvGroups.frame.size.width / 2 + self.clvGroups.contentOffset.x, self.clvGroups.frame.size.height / 2 + self.clvGroups.contentOffset.y); if let ip = self.clvGroups.indexPathForItemAtPoint(location){ groupToUpdate.icon = self.dataSource![ip.row].icon } 

您必须记住集合视图的滚动视图。