uitableview headerViewForSection:总是返回nil

我有一个自定义标题视图的表,无论何时,或者我select什么值的部分,我总是得到零值。 我有另一个表具有相同的问题。

我可以看到标题视图,如果我打印[tableview子视图]的值,但我不知道为什么该方法不会返回任何东西。

我想要做的是得到一个activityIndi​​cator在headerview中,并启动它或通过方法调用来停止它。

标题总是画好,但我不能得到一个参考。 另外,调用headerViewForSection:不调用委托方法,这是正常的吗?

footerViewForSection:具有相同的问题

一些代码:

 - (UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { NSArray* objs = [[NSBundle mainBundle] loadNibNamed:@"iPadTableCells" owner:nil options:nil]; UIView* header = [objs objectAtIndex: 0]; UIActivityIndicatorView* activityIndicator = (UIActivityIndicatorView*) [header viewWithTag:5]; [activityIndicator startAnimating] return header; } 

从任何方法:

  UIView* headerView = [tableview headerViewForSection: section]; //returns nil if (headerView) { UIActivityIndicatorView* activityIndicator = (UIActivityIndicatorView*)[headerView viewWithTag: 5]; [activityIndicator stopAnimating]; } 

回答

从文档:

要使表视图知道您的页眉或页脚视图,您需要注册它。 你可以使用UITableView的registerNib:forCellReuseIdentifier:registerClass:forCellReuseIdentifier:方法。

所以你需要注册nib,然后使用重用标识符来获取它,而不是直接从应用程序包中拉出来,这就是你现在正在做的。

…如果你想使用headerViewForSection方法。

备用答案

或者,您可以检查是否在viewForHeaderInSection method内继续旋转,然后发送只是调用:

 [self.tableView beginUpdates]; [self.tableView endUpdates]; 

刷新节标题。

(请注意,这种替代方法会破坏并重新创build您的整个视图,所以如果您的桌子上有大量的数据,可能效率不高。)

这个问题已经有一段时间了,最​​近我遇到了类似的问题,并且在这里问自己的问题: UITableView-headerViewForSection返回(null)
我相信我有答案。


先决条件步骤:

  1. 创build一个UITableViewHeaderFooterView子类并将其命名为CustomHeaderView
  2. 为这个类创build一个视图接口nib文件( 显然你在这里命名为iPadTableCells
  3. 在xib中,selectView&in的Identity Inspector
    • 自定义类指定为CustomHeaderView
  4. 做一个属性,合成并连接到xib
    • @property (strong, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

使用下面的代码:

 - (UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *HeaderIdentifier = @"header"; CustomHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier]; if(!header) { NSArray* objs = [[NSBundle mainBundle] loadNibNamed:@"iPadTableCells" owner:nil options:nil]; header = [objs objectAtIndex: 0]; } [header.activityIndicator startAnimating]; return header; } 

那么你可以这样访问它:

 CustomHeaderView *headerView = (CustomHeaderView*)[tableView headerViewForSection:section]; [headerView.activityIndicator stopAnimating]; 

迅速

所有你需要的是为你需要返回的标题视图创build一个UITableViewHeaderFooterView的实例

  func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let sectionHeaderView = UITableViewHeaderFooterView() //customize your view here return sectionHeaderView }