简体   繁体   中英

How do I get the tableView by the custom cell?

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

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: .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM