Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Cell position in UITableview

I am trying to get position of cell in tableview. from this code i am getting cell position

int numberOfSections = [UITableView numberOfSections];
int numberOfRows = 0;
NSIndexPath *tempIndexPath = nil;
UITableViewCell *tempCell = nil;
for(int i=0;i<numberOfSections;i++)
{
     numberOfRows = [UITableView numberOfRowsInSection:i];
     for(int j=0;j<numberOfRows;j++
     {
           tempIndexPath = [NSIndexPath indexPathForRow:j inSection:i];
           tempCell = [UITableView cellForRowAtIndexPath:tempIndexPath];
           NSLog("Y postion for cell at (Row = %d,Section = %d) is :%f",tempCell.frame.origin.y);
     }  
}

it is calculating y axes of cell in tableview but my problem is i want to get the cell position in the visible area of tableview rect. ie if table view has size cgrectmake(0,0,200,500) and cell height is 100 pixels. so tableview will show 5 rows. if i scroll down and select 7th row. i will get its y axes 700. but the cell will be within (0,0,200,500) frame. How can I get cell location within this frame (0,0,200,500).

like image 295
TalaT Avatar asked Jul 08 '11 11:07

TalaT


2 Answers

To get the position of a UITableViewCell relative to the view, in which the tableView is located (e.g. relative to your visible area):


Swift 5 (and also Swift 4, Swift 3):

let rectOfCellInTableView = tableView.rectForRow(at: indexPath)
let rectOfCellInSuperview = tableView.convert(rectOfCellInTableView, to: tableView.superview)
    
print("Y of Cell is: \(rectOfCellInSuperview.origin.y)")

Objective-C:

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

NSLog(@"Y of Cell is: %f", rectOfCellInSuperview.origin.y);

Swift 2 (really?):

let rectOfCellInTableView = tableView.rectForRowAtIndexPath(indexPath)
let rectOfCellInSuperview = tableView.convertRect(rectOfCellInTableView, toView: tableView.superview)

print("Y of Cell is: \(rectOfCellInSuperview.origin.y)")
like image 103
Nikolay Suvandzhiev Avatar answered Oct 21 '22 21:10

Nikolay Suvandzhiev


NOTE:I hope, question might have updated again, please use the other answers that may applicable to you.

You can use the visibleCells method which will return the currently visible cells in your tableview:

NSArray *visibleCellsList=[tableview visibleCells];

for (UITableViewCell* currentCell in visibleCellsList) {

    NSLog(@"cell : %@ \n\n",currentCell.textLabel.text);

}
like image 26
Vijay-Apple-Dev.blogspot.com Avatar answered Oct 21 '22 22:10

Vijay-Apple-Dev.blogspot.com