【问题标题】:Get Cell position in UITableview获取 UITableview 中的单元格位置
【发布时间】:2011-10-01 05:23:09
【问题描述】:

我正在尝试获取单元格在表格视图中的位置。从这段代码中我得到了单元格的位置

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)。

【问题讨论】:

  • 您的日志错误NSLog("(Row = %d,Section = %d) 单元格的 Y 位置为 :%f",tempCell.frame.origin.y);

标签: iphone uitableview


【解决方案1】:

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


Swift 5(还有 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)")

目标-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)")

【讨论】:

  • 你是否知道如何相对于表格的滚动视图的contentView 来获取它? IE。相对于可滚动内容的顶部?
  • 我很惊讶。谢谢。虽然我迟到了:如果你能解释一下为什么你的答案有效,那将非常有帮助。
  • 将其设为已接受的答案!
【解决方案2】:

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

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

NSArray *visibleCellsList=[tableview visibleCells];

for (UITableViewCell* currentCell in visibleCellsList) {

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

}

【讨论】:

    【解决方案3】:

    我是这样做的:

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    

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

    【讨论】:

      猜你喜欢
      • 2011-06-27
      • 2012-08-19
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多