在UITableview中获取Cell位置

时间:2011-07-08 11:47:43

标签: iphone uitableview

我想在tableview中获取单元格的位置。从这段代码我得到单元格位置

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);
     }  
}

它是在tableview中计算单元格的y轴,但我的问题是我想在tableview rect的可见区域中获取单元格位置。即如果表视图的大小为cgrectmake(0,0,200,500) 和单元格高度为100像素。所以tableview将显示5行。如果我向下滚动并选择第7行。我将得到它的y轴700.但是单元格将在(0,0,200,500)帧内。 如何在此框架内获取单元格位置(0,0,200,500)。

3 个答案:

答案 0 :(得分:195)

获取UITableViewCell相对于视图的位置(例如,相对于您的可见区域):


Swift 3,Swift 4:

let rectOfCellInTableView = tableView.rectForRow(at: indexPath)
let rectOfCellInSuperview = tableView.convert(rectOfCellInTableView, to: tableView.superview)

print("Y of Cell is: \(rectOfCellInSuperview.origin.y)")


目标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:

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

print("Y of Cell is: \(rectOfCellInSuperview.origin.y)")

答案 1 :(得分:11)

注意:我希望,问题可能会再次更新,请使用可能适用于您的其他答案。

您可以使用visibleCells方法返回表格视图中当前可见的单元格:

NSArray *visibleCellsList=[tableview visibleCells];

for (UITableViewCell* currentCell in visibleCellsList) {

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

}

答案 2 :(得分:0)

我是这样做的:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

这就是我所要做的一切,而不是cell.framecell.bounds等等。