Friday, June 7, 2013

UITableView indexPathForRowAtPoint example in Objective C (iOS).

UITableView indexPathForRowAtPoint

Returns an index path identifying the row and section at the given point.

- (NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point

A point in the local coordinate system of the receiver (the table view'€™s bounds).

Return Value of [UITableView indexPathForRowAtPoint]
An index path representing the row and section associated with point or nil if the point is out of the bounds of any row.

UITableView indexPathForRowAtPoint example.
In Apple's Accessory sample the following method is used:

[button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
Then in touch handler touch coordinate retrieved and index path is calculated from that coordinate:

- (void)checkButtonTapped:(id)sender
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)

Example of [UITableView indexPathForRowAtPoint].
- (void)buttonPressedAction:(id)sender {

NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];

do stuff with the indexPath...

UITableView indexPathForRowAtPoint example.
In viewDidLoad:

UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc]
    initWithTarget:self action:@selector(handleSwipe:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.view addGestureRecognizer:recognizer];
[recognizer release];
Then, in the handleSwipe method:

- (void)handleSwipe:(UISwipeGestureRecognizer *) recognizer
    //might need to check if swipe has ended (otherwise not time to handle yet)
    if (recognizer.state != UIGestureRecognizerStateEnded)

    CGPoint location = [recognizer locationInView:tableView]; //not self.view 
    NSIndexPath *selectedIndexPath = [tableView indexPathForRowAtPoint:location];

    if (selectedIndexPath != nil)
        //user swiped on a tableview cell
        //user did not swipe on a tableview cell

End of UITableView indexPathForRowAtPoint example article.