2017-09-19 56 views
0

如何通过CustomCell中的自定义单元格获取tableView?如何通过自定义单元格获取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 
+0

没有理由让单元访问它所在的表。请解释为什么你认为你需要这个。可能有更好的解决方案。 – rmaddy

+0

有详细页面,使用不同的单元格。有两个视图的标签视图,我通常在其中添加两个控制器。所以我必须让超级视图控制器添加子控制器。我不知道我的描述,我的英文不好: - ) –

回答

0

要回答这个问题,苹果不会为提供一个公共的API,你将不得不使用它所谓有关视图层次的事。 tableViewCell将始终是tableView的一部分。从技术上讲,一个tableViewCell将始终在一个tableView的视图层次结构一个tableViewCell总是会有一些超级查看那里是一个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; 
    } 
} 

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

+0

感谢您的回答,这真的对我很好。 : - ) –

相关问题