ios 如何从 Cell 中获取 UITableViewCell indexPath?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15711889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:57:00  来源:igfitidea点击:

How to get UITableViewCell indexPath from the Cell?

iphoneiosobjective-cxcodecocoa

提问by sinθ

How do I, from a cell, get its indexPathin a UITableView?

我如何从一个细胞,得到了indexPathUITableView

I've searched around stack overflow and google, but all the information is on the other way around. Is there some way to access the superView/UITableViewand then search for the cell?

我搜索了堆栈溢出和谷歌,但所有信息都在相反的方向。有没有办法访问superView/UITableView然后搜索单元格?

More information about the context: there are two classes that I have, one is called Cueand one is called CueTableCell(which is a subclass of UITableViewCell) CueTableCellis the visual representation of Cue(both classes have pointers to each other). Cueobjects are in a linked list and when the user performs a certain command, the visual representation (the CueTableCell) of the next Cueneeds to be selected. So the Cueclass calls the selectmethod on the next Cuein the list, which retrieves the UITableViewfrom the celland calls its selectRowAtIndexPath:animated:scrollPosition:, for which it needs the indexPathof the UITableViewCell.

关于上下文的更多信息:我有两个类,一个被调用Cue,一个被调用CueTableCell(它是 的子类UITableViewCellCueTableCellCue(两个类都有彼此的指针)的可视化表示。Cue对象在链表中,当用户执行某个命令时,需要选择CueTableCell下一个的视觉表示()Cue。因此,Cue该类调用列表中select下一个的方法,该方法从Cue中检索并调用其,为此它需要的。UITableViewcellselectRowAtIndexPath:animated:scrollPosition:indexPathUITableViewCell

回答by Mundi

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

It helps reading the UITableView documentation, even if this is by some regarded to be controversial (see comments below).

它有助于阅读UITableView 文档,即使有人认为这是有争议的(请参阅下面的评论)。

The cell has no business knowing what its index path is. The controllershould contain any code that manipulates UI elements based on the data model or that modifies data based on UI interactions. (See MVC.)

单元不知道它的索引路径是什么。该控制器应该包含任何代码,基于所述数据模型或基于UI交互修改数据操纵UI元素。(请参阅MVC。)

回答by Pepper

Try with this from your UITableViewCell:

从你的 UITableViewCell 试试这个:

NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];

EDIT: Seems this doesn't work on iOS 8.1.2 and further. Thanks to Chris Prince for pointing it.

编辑:似乎这不适用于 iOS 8.1.2 及更高版本。感谢克里斯普林斯指出它。

回答by AITAALI_ABDERRAHMANE

You can try this simple tip:

你可以试试这个简单的提示:

on your UITableViewCellClass :

在你的UITableViewCell课上:

@property NSInteger myCellIndex; //or add directly your indexPath 

and on your cellForRowAtIndexPathmethod :

和你的cellForRowAtIndexPath方法:

...
[cell setMyCellIndex : indexPath.row]

now, you can retrieve your cell index anywhere

现在,您可以在任何地方检索您的单元格索引

回答by mikeho

To address those who say "this is a bad idea", in my case, my need for this is that I have a button on my UITableViewCellthat, when pressed, is a segue to another view. Since this is not a selection on the cell itself, [self.tableView indexPathForSelectedRow]does not work.

为了解决那些说“这是一个坏主意”的人,在我的情况下,我需要的是我的按钮上有一个按钮UITableViewCell,当按下时,是另一个视图的segue。由于这不是单元格本身的选择,[self.tableView indexPathForSelectedRow]因此不起作用。

This leaves me two options:

这给我留下了两个选择:

  1. Store the object that I need to pass into the view in the table cell itself.While this would work, it would defeat the point of me having an NSFetchedResultsControllerbecause I do notwant to store all the objects in memory, especially if the table is long.
  2. Retrieve the item from the fetch controller using the index path.Yes, it seems ugly that I have to go figure out the NSIndexPathby a hack, but it's ultimately less expensive than storing objects in memory.
  1. 将我需要传递到表格单元格本身中的视图的对象存储起来。虽然这工作,它会破坏我的点有一个NSFetchedResultsController,因为我没有做想所有对象存储在内存中,特别是如果该表是长。
  2. 使用索引路径从 fetch 控制器中检索项目。是的,我必须NSIndexPath通过 hack来弄清楚这似乎很难看,但它最终比将对象存储在内存中要便宜。

indexPathForCell:is the correct method to use, but here's how I would do it (this code is assumed to be implemented in a subclass of UITableViewCell:

indexPathForCell:是正确的使用方法,但这是我的方法(假定此代码在以下子类中实现UITableViewCell

// uses the indexPathForCell to return the indexPath for itself
- (NSIndexPath *)getIndexPath {
    return [[self getTableView] indexPathForCell:self];
}

// retrieve the table view from self   
- (UITableView *)getTableView {
    // get the superview of this class, note the camel-case V to differentiate
    // from the class' superview property.
    UIView *superView = self.superview;

    /*
      check to see that *superView != nil* (if it is then we've walked up the
      entire chain of views without finding a UITableView object) and whether
      the superView is a UITableView.
    */
    while (superView && ![superView isKindOfClass:[UITableView class]]) {
        superView = superView.superview;
    }

    // if superView != nil, then it means we found the UITableView that contains
    // the cell.
    if (superView) {
        // cast the object and return
        return (UITableView *)superView;
    }

    // we did not find any UITableView
    return nil;
}

P.S. My real code does access all this from the table view, but I'm giving an example of why someone might want to do something like this in the table cell directly.

PS 我的真实代码确实从表格视图访问了所有这些,但我举了一个例子,说明为什么有人可能想直接在表格单元格中做这样的事情。

回答by Chanchal Raj

  1. Put a weak tableView property in cell's .h file like:

    @property (weak,nonatomic)UITableView *tableView;

  2. Assign the property in cellForRowAtIndex method like:

    cell.tableView = tableView;

  3. Now wherever you need the indexPath of cell:

    NSIndexPath *indexPath = [cell.tableView indexPathForCell:cell];

  1. 在单元格的 .h 文件中放置一个弱 tableView 属性,例如:

    @property (weak,nonatomic)UITableView *tableView;

  2. 在 cellForRowAtIndex 方法中分配属性,如:

    cell.tableView = tableView;

  3. 现在,无论您在哪里需要单元格的 indexPath:

    NSIndexPath *indexPath = [cell.tableView indexPathForCell:cell];

回答by Gevorg Ghukasyan

For swift

为迅速

let indexPath :NSIndexPath = (self.superview.superview as! UITableView).indexPathForCell(self)!

回答by banan3'14

On iOS 11.0, you can use UITableView.indexPathForRow(at point: CGPoint) -> IndexPath?:

在 iOS 11.0 上,您可以使用UITableView.indexPathForRow(at point: CGPoint) -> IndexPath?

if let indexPath = tableView.indexPathForRow(at: cell.center) {
    tableView.selectRow
    (at: indexPath, animated: true, scrollPosition: .middle)
}

It gets the center point of the cell and then the tableView returns the indexPath corresponding to that point.

它获取单元格的中心点,然后 tableView 返回与该点对应的 indexPath。

回答by Cescy

The answer to this question actually helped me a lot.

这个问题的答案实际上对我帮助很大。

I used NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];

我用了 NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];

The senderin my case was a UITableViewCelland comes from the prepareForSeguemethod.

sender在我的情况是UITableViewCell和来自prepareForSegue法。

I used this because I did nothave a TableViewControllerbut i had UITableView property outlet

我用这个,因为我根本TableViewController,但我有UITableView property outlet

I needed to find out the title of the Celland hence needed to know the indexPath of it.

我需要找出 的标题,Cell因此需要知道它的 indexPath。

Hope this helps anyone!

希望这可以帮助任何人!

回答by m.eldehairy

try this (it only works if the tableView has only one section and all cells has equal heights) :

试试这个(它只适用于 tableView 只有一个部分并且所有单元格具有相同的高度):

//get current cell rectangle relative to its superview
CGRect r = [self convertRect:self.frame toView:self.superview];

//get cell index
int index = r.origin.y / r.size.height;

回答by Yogesh Kumar

Try with this from your UITableViewCell:

从你的 UITableViewCell 试试这个:

NSIndexPath *indexPath = [(UITableView *)self.superview.superview indexPathForCell:self];