0

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

- (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
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Sunny_Ken
  • 11
  • 4
  • There is no reason for a cell to have any access to the table it is in. Please explain why you think you need this. There is probably a better solution. – rmaddy Sep 20 '17 at 03:26
  • There are detail pages, used different cells in it. have a tab view for two view, I usually add two controller in it. So I have to get the super view controller to add children controller. I do not do you know my describe, my english is not good : - ) – Sunny_Ken Sep 21 '17 at 15:21

1 Answers1

0

To answer the question, Apple does not provide a public API for that and you would have to do it using what is known about view hierarchies. A tableViewCell would always be part of a tableView. Technically, a tableViewCell would always be in a tableView's view hierarchy or a tableViewCell would always have some superview out there that is a tableView. Here is a method similar to 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;
    }
}

More generally, Apple did not provide such public API for a reason. It is indeed best practice for the cell to use other mechanisms to avoid querying the tableView, like using properties that can be configured at runtime by the user of the class in tableView:cellForRowAtIndexPath:.