Getting long pressed cell's position

Discussion in 'iOS Programming' started by erdinc27, Mar 15, 2017.

  1. erdinc27 macrumors regular

    Jul 20, 2011
    In the tableview i added long press gesture to each cell. I try to get the current position of long pressed cell. But i couldn' t achieve it. Here how i try to do
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
                cell.contentView.tag = indexPath.row;
                UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(otherCellLongPressed:)];
                [cell.contentView addGestureRecognizer:gesture];
    - (void) otherCellLongPressed:(UILongPressGestureRecognizer *) gesture {
        if (gesture.state == UIGestureRecognizerStateEnded) {
     NSIndexPath *indexPath = [NSIndexPath indexPathWithIndex:gesture.view.tag];
    CGRect rectOfCellInTableView = [self.mainTableView rectForRowAtIndexPath: indexPath];
    CGRect rectOfCellInSuperview = [self.mainTableView convertRect: rectOfCellInTableView toView: self.mainTableView.superview];
    but here rectOfCellInSuperview's x, y, width and height is always 0. No matter which cell is long pressed. How can i get the cell's position in superview.
  2. Ubuntu macrumors 68000


    Jul 3, 2005
    To be honest I would suggest one UILongPressGestureRecognizer on the UITableView and then in your UILongPressGestureRecognizer method I would call the gestureRecognizer's locationInView (passing in the UITableView as the view) to get a CGPoint and call the UITableView's indexPathForRowAtPoint: method (with this point I now have) to get the indexPath. You could then call rectForRowAtIndexPath.

    Hope this helps.
  3. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    Here's how I'd do it. The cell adds the gestureRecognizer to itself and sets itself as the target. The cell has a delegate protocol where it calls its delegate when the long press occurs and returns itself and its indexPath. In cellForRowAtIndexPath the view controller sets the indexPath and delegate on the cell. No monkey business with rects and superviews and calculations. The cell knows its indexPath and it tells it to its delegate.

    BTW, I think you're not calculating the indexPath correctly. You need to specify the section and row.
  4. erdinc27 thread starter macrumors regular

    Jul 20, 2011
    Thank you for suggestion guys. As @PhoneyDeveloper guessed i couldnt get the indexPath correctly. Now i get it like that.
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:gesture.view.tag inSection:0];
    It works as i intended.

Share This Page

3 March 15, 2017