Bertges
Bertges

Reputation: 23

How to get the position of tableviewcell after scrolling the tableview

I want to get the position of UITableVIewCell relative to the screen, not relative to tableview. So, if I scroll the tableview, the position is updated.

Upvotes: 2

Views: 2812

Answers (3)

jordanperry
jordanperry

Reputation: 3378

Use the -[UITableView rectForRowAtIndexPath:] method. Keep in mind that if you attempt to get this when the cell is off screen you will get unexpected results. You can then convert it to your view controller's view (which i think is what you mean by screen) with the -[UIView convertRect:toView:] method.

Ref: https://developer.apple.com/library/ios/documentation/uikit/reference/UITableView_Class/Reference/Reference.html#jumpTo_49

https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#jumpTo_65

Upvotes: 0

nzs
nzs

Reputation: 3252

You should use two steps to achieve this:

  1. Get the CGRect information for a selected cell/header or footer by using one of these methods of UITableView:
- (CGRect)rectForHeaderInSection:(NSInteger)section;
- (CGRect)rectForFooterInSection:(NSInteger)section;
- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath;

2. Convert the CGRect to table's container view by using UITableView's convertRect method. Eg. to get the current pos of the first header you can use this code:

    CGRect rect = [mytable convertRect:[mytable rectForHeaderInSection:0] toView:[mytable superview]];

If you want these above dinamically you might want to include this code in UITableView's delegate method:

  - (void)scrollViewDidScroll:(UIScrollView *)scrollView_ {.....

One example what I've done using similar techniques is at github - how to make table header row fixed:

https://github.com/codedad/SO_Fixed_TableHeader_iOS

Hope it helps you!

Upvotes: 6

Christopher Nassar
Christopher Nassar

Reputation: 554

You need to get position from child to parent:

float x = cell.frame.origin.x;
float y = cell.frame.origin.y;

UIView* parent = cell.parent;

while(parent != nil)
{
    x += parent.frame.origin.x;
    y += parent.frame.origin.y;
    parent = parent.parent;
}

Upvotes: 0

Related Questions