[英]How do I get the tableView by the custom cell?
如何通過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
為了回答這個問題,Apple沒有為此提供公共API,您必須使用關於視圖層次結構的已知知識來做到這一點。 tableViewCell將始終是tableView的一部分。 從技術上講, tableViewCell始終位於tableView的視圖層次結構中,或者tableViewCell始終始終具有某個名為tableView的超級視圖 。 這是與此類似的方法:
- (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;
}
}
更一般而言,Apple出於某種原因未提供此類公共API。 實際上,單元格的最佳實踐是使用其他機制來避免查詢tableView,例如使用可在運行時由tableView:cellForRowAtIndexPath:
中的類的用戶配置的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.