如何通过自定义单元格获取tableView?

时间:2017-09-19 20:27:26

标签: ios objective-c uitableview

如何通过CustomCell中的自定义单元格获取tableView?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];
     return cell;
}

@implementation CustomCell 
- (void)awakeFromNib {
    [super awakeFromNib];

    // How do I get tableView by custom cell in the CustomCell?

}
@end

1 个答案:

答案 0 :(得分:0)

要回答这个问题,Apple不会为此提供公共API,您必须使用已知的视图层次结构来完成此操作。 tableViewCell始终是tableView的一部分。从技术上讲, tableViewCell总是在tableView的视图层次结构中 tableViewCell总会有一些superview,那就是tableView 。这是一种类似于this one的方法:

- (UITableView *)getParentTableView:(UITableViewCell *)cell {
    UIView *parent = cell.superview;
    while ( ![parent isKindOfClass:[UITableView class]] && parent.superview){
        parent = parent.superview;
    }
    if ([parent isKindOfClass:[UITableView class]]){
        UITableView *tableView = (UITableView *) parent;
        return tableView;
    } else {
        // This should not be reached unless really you do bad practice (like creating the cell with [[UITableView alloc] init])
        // This means that the cell is not part of a tableView's view hierarchy
        // @throw NSInternalInconsistencyException
        return nil;
    }
}

更一般地说,Apple没有提供这样的公共API是有原因的。单元格最好使用其他机制来避免查询tableView,例如使用tableView:cellForRowAtIndexPath:中类的用户可以在运行时配置的属性。