我有一个有四个 Collection View 的 View 。我正在尝试检测收到长按手势的单元格。我安装了手势识别器,它对于 View 顶部的 Collection View (物理上不是分层的)工作正常,但不适用于其余 View 。
试试下面的代码:
CGPoint p = [gestureRecognizer locationInView:self.view];
NSIndexPath *indexPath;
if ([self.TopCollectionView indexPathForItemAtPoint:p]){
indexPath = [self.TopCollectionView indexPathForItemAtPoint:p];
_lilCell = (ArticlePanelViewCell *)[self.TopCollectionView cellForItemAtIndexPath:indexPath];
NSLog(@"top");
}else if([self.MiddleCollectionView indexPathForItemAtPoint:p]){
indexPath = [self.MiddleCollectionView indexPathForItemAtPoint:p];
_lilCell = (ArticlePanelViewCell *)[self.MiddleCollectionView cellForItemAtIndexPath:indexPath];
NSLog(@"middle");
}else if([self.BottomCollectionView indexPathForItemAtPoint:p]){
indexPath = [self.BottomCollectionView indexPathForItemAtPoint:p];
_lilCell = (ArticlePanelViewCell *)[self.BottomCollectionView cellForItemAtIndexPath:indexPath];
NSLog(@"bottom");
}else if([self.ExtraCollectionView indexPathForItemAtPoint:p]){
indexPath = [self.ExtraCollectionView indexPathForItemAtPoint:p];
_lilCell = (ArticlePanelViewCell *)[self.ExtraCollectionView cellForItemAtIndexPath:indexPath];
NSLog(@"bottom");
}else {
NSLog(@"Long press detected outside the content panel area");
}
它适用于 TopCollectionView 而不是其余的。点 p 确实显示了正确的坐标。手势识别器回调位于包含 4 个 Collection View 的 View Controller 中,因为它是 subview 。
最佳答案
根据docs
方法indexPathForItemAtPoint
预计采取CGPoint
在其坐标系中。
因此,要解决您的问题,您应该添加更多代码。
首先你应该识别出哪个collectionView frame
有CGPoint
里面。
你可以用这个方法bool CGRectContainsPoint(CGRect rect, CGPoint point);
然后,当您知道触摸是在哪个 collectionView 中时,您应该将其转换为它的坐标系
CGPoint p = [self.view convertPoint:p toView:collectionView];
然后调用
indexPath = [self.theCollectionView indexPathForItemAtPoint:p];
请注意:
如果您在单元格之间点击(而不是直接在实际单元格上),您将不会获得单元格的
indexPath
关于ios - UICollectionView indexPathForItemAtPoint 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35181809/