简体   繁体   English

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

[英]How do I get the tableView by the custom cell?

How do I get tableView by custom cell in the CustomCell? 如何通过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

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. 为了回答这个问题,Apple没有为此提供公共API,您必须使用关于视图层次结构的已知知识来做到这一点。 A tableViewCell would always be part of a tableView. tableViewCell将始终是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 . 从技术上讲, tableViewCell始终位于tableView的视图层次结构中,或者tableViewCell始终始终具有某个名为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. 更一般而言,Apple出于某种原因未提供此类公共API。 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: . 实际上,单元格的最佳实践是使用其他机制来避免查询tableView,例如使用可在运行时由tableView:cellForRowAtIndexPath:中的类的用户配置的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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