2017-09-19 51 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

感謝您的回答,這真的對我很好。 : - ) –

相關問題