sin*_*inθ 70 iphone xcode cocoa objective-c ios
我如何从一个细胞,得到了indexPath在UITableView?
我搜索了堆栈溢出和谷歌,但所有的信息是相反的.有没有办法访问superView/ UITableView然后搜索单元格?
关于上下文的更多信息:我有两个类,一个被调用Cue,一个被调用CueTableCell(它的子类UITableViewCell)CueTableCell是可视化表示Cue(两个类都有指向彼此的指针).Cue对象在链表中,当用户执行某个命令时,需要选择CueTableCell下一个的可视表示()Cue.因此Cue类调用select的下一个方法Cue列表,以检索UITableView从cell并调用它selectRowAtIndexPath:animated:scrollPosition:,为它需要indexPath的UITableViewCell.
Mun*_*ndi 133
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
它有助于阅读文档,即使这被认为是有争议的(见下面的评论).
该单元没有业务知道它的索引路径是什么.该控制器应该包含任何能够根据数据模型的UI元素的任何代码或修改基于UI交互的数据.(见MVC.)
Pep*_*per 25
从你的UITableViewCell尝试:
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
编辑:似乎这不适用于iOS 8.1.2及更高版本.感谢Chris Prince的指点.
AIT*_*ANE 11
您可以尝试这个简单的提示:
在你的UITableViewCell班级:
@property NSInteger myCellIndex; //or add directly your indexPath 
并根据您的cellForRowAtIndexPath方法:
...
[cell setMyCellIndex : indexPath.row]
现在,您可以在任何地方检索您的单元索引
mik*_*eho 10
为了解决那些说"这是一个坏主意"的人,在我的情况下,我需要的是我有一个按钮UITableViewCell,当按下时,它是另一个视图.由于这不是细胞本身的选择,[self.tableView indexPathForSelectedRow]不起作用.
这给我留下了两个选择:
NSFetchedResultsController,因为我不做要存储在内存中的所有对象,特别是如果该表是长.NSIndexPath通过黑客来弄清楚,但它最终比在内存中存储对象便宜.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;
}
PS我的真实代码可以从表格视图中访问所有这些,但我举一个例子,说明为什么有人可能想直接在表格单元格中执行此类操作.
Cha*_*Raj 10
在cell的.h文件中放置一个弱的tableView属性,如:
@property (weak,nonatomic)UITableView *tableView;
在cellForRowAtIndex方法中分配属性,如:
cell.tableView = tableView;
现在,只要你需要cellPath的indexPath:
NSIndexPath *indexPath = [cell.tableView indexPathForCell:cell];
对于迅捷
let indexPath :NSIndexPath = (self.superview.superview as! UITableView).indexPathForCell(self)!
| 归档时间: | 
 | 
| 查看次数: | 86885 次 | 
| 最近记录: |