Friday, June 7, 2013

UITableView rectForRowAtIndexPath example in Objective C (iOS).


UITableView rectForRowAtIndexPath

Returns the drawing area for a row identified by index path.

- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath

Parameters
indexPath
An index path object that identifies a row by its index and its section index.

Return Value of [UITableView rectForRowAtIndexPath]
A rectangle defining the area in which the table view draws the row or CGRectZero if indexPath is invalid.

UITableView rectForRowAtIndexPath example.
The first step is to use

CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];

which will report the CGRect of a cell within the tableView. However, this value does not change as the tableView scrolls. It is the position relative to the first row of the table (and not the first visible row). To get the position of the cell on the screen you have to convert it to the superviews coordinate system using

CGRect rect = [tableView convertRect:rectInTableView toView:[tableView superview]];

So the following line does it all

CGRect rect = [tableView convertRect:[tableView rectForRowAtIndexPath:indexPath] toView:[tableView superview]]; .

Example of [UITableView rectForRowAtIndexPath].
CGRect rect = [aTableView rectForRowAtIndexPath:indexPath];

//create a 10 pixel width rect at the center of the cell

rect.origin.x = (rect.size.width - 10.0) / 2.0;
rect.size.width = 10.0; 

[self.addExpensePopoverController presentPopoverFromRect:rect inView:aTableView permittedArrowDirections:UIPopoverArrowDirectionAny  animated:YES]; 

UITableView rectForRowAtIndexPath example.
CGRect rowRect = [tableView rectForRowAtIndexPath:indexPath];
CGPoint offsetPoint = [self.infoTableView contentOffset];

// remove the offset from the rowRect
rowRect.origin.y -= offsetPoint.y;

// Move to the actual position of the tableView
rowRect.origin.x += self.infoTableView.frame.origin.x;
rowRect.origin.y += self.infoTableView.frame.origin.y;

End of UITableView rectForRowAtIndexPath example article.