在UITableview中获取Cell位置

Tal*_*laT 36 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);
     }  
}
Run Code Online (Sandbox Code Playgroud)

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

Nik*_*iev 201

获取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)")
Run Code Online (Sandbox Code Playgroud)


Objective-C的:

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

NSLog(@"Y of Cell is: %f", rectOfCellInSuperview.origin.y);
Run Code Online (Sandbox Code Playgroud)


斯威夫特2:

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

print("Y of Cell is: \(rectOfCellInSuperview.origin.y)")
Run Code Online (Sandbox Code Playgroud)

  • 将其作为已接受的答案! (2认同)

Vij*_*com 11

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

您可以使用visibleCells将返回tableview中当前可见单元格的方法:

NSArray *visibleCellsList=[tableview visibleCells];

for (UITableViewCell* currentCell in visibleCellsList) {

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

}
Run Code Online (Sandbox Code Playgroud)