Get CGPoint inside didSelectItemAtIndexPath method of CollectionView

Is there a way that I can get the coordinates of the clicked point inside the collectionViewCell? I want to make Method A if I clicked on a rectangle with Y <50, and Method B if Y> 50.

+3


source to share


2 answers


There is also option B to subclass the UITableViewCell and get the location from the class 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

      



Then select a location from the 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
    }
}

      

+9


source


Assuming you have a custom one UICollectionViewCell

, you can add UITapGestureRecognizer

to the cell and get the touch point in the touchhesBegan handler. Like this:



 //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];
   }
}

      

+1


source







All Articles