在CollectionView的didSelectItemAtIndexPath方法中获取CGPoint

时间:2014-11-03 07:39:44

标签: ios iphone ipad uicollectionview cgpoint

有没有办法可以在collectionViewCell中获取点击点的坐标?如果我点击带有Y坐标<的矩形,我想做方法A.如果Y> 50,则方法B如图50所示。

2 个答案:

答案 0 :(得分:9)

还有选项B,用于子类化UITableViewCell并从UIResponder类获取位置:

@interface CustomTableViewCell : UITableViewCell

@property (nonatomic) CGPoint clickedLocation;

@end

@implementation CustomTableViewCell

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    self.clickedLocation = [touch locationInView:touch.view];
}

@end

然后从TableViewCell获取自己的位置:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //get the cell
    CustomTableViewCell *cell = (CustomTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    //get where the user clicked
    if (cell.clickedLocation.Y<50) {
        //Method A
    }
    else {
        //Method B
    }
}

答案 1 :(得分:1)

假设您有自定义UICollectionViewCell,则可以向单元格添加UITapGestureRecognizer并获取touchesBegan处理程序中的触摸点。像这样:

 //add gesture recognizer to cell
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] init];
[cell addGestureRecognizer:singleTap];

//handler
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *touch = [touches anyObject];
   CGPoint touchPoint = [touch locationInView:self.view];

   if (touchPoint.y <= 50) {
      [self methodA];
   }
   else {
      [self methodB];
   }
}