如何在self.view中获取UICollectionViewCell的位置?

时间:2014-05-15 20:34:23

标签: ios objective-c

我使用下面的代码来获取触摸时单元格的位置。 但是,当UICollectionView.bounds.size.width> 320,或> 640,“origin.x”经常返回> 320,例如,657,469。因为细胞内有一些图像。所以当我触摸第二页上的单元格时。返回的值X可以是368.0或其他值。

我只需要在当前视图中获取值X(320 * 480)。

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath]; - (void)viewDidLoad { // attach long press gesture to collectionView UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; lpgr.minimumPressDuration = .5; //seconds lpgr.delegate = self; [self.collectionView addGestureRecognizer:lpgr]; } -(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer { if (gestureRecognizer.state != UIGestureRecognizerStateEnded) { return; } CGPoint p = [gestureRecognizer locationInView:self.collectionView]; NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:p]; if (indexPath == nil){ NSLog(@"couldn't find index path"); } else { // get the cell at indexPath (the one you long pressed) UICollectionViewCell* cell = [self.collectionView cellForItemAtIndexPath:indexPath]; // do stuff with the cell } }

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您的收藏视图可能会横向显示多个页面。假设这些页面是帧宽,你可以这样做:

int xVal = (int)p.x % (int)self.view.frame.size.width;

请记住,您将失去小数精度。