Getting long pressed cell's position

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

  1. erdinc27 macrumors regular

    Joined:
    Jul 20, 2011
    #1
    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
    Code:
    - (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];
    }
    
    Code:
    - (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

    Ubuntu

    Joined:
    Jul 3, 2005
    Location:
    UK/US
    #2
    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 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #3
    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

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

Share This Page