viewForHeaderInSection - 没有标题返回什么?

Gen*_*ike 7 objective-c uitableview ios

我有一个嵌入UIViewController其中的几个UITableView.对于某些表,我需要显示带有多个标签的自定义标题视图.对于其他表格,我根本不想显示标题(也就是说,我希望第一个单元格位于myTable2框架的顶部myTable2).这是我的大致内容:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.myTable1)
    // Wants Custom Header
    {        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.contentSize.width,20);

        // ... Do stuff to customize view ...

        return view;
    }
    elseIf (tableView == self.myTable2)
    // Wants No header
    {
        return nil;
        // also tried
        // return [[UIView alloc] initWithFrame:CGRectMake(0,0,0,0)];
        // but that didn't work either
    }
}
Run Code Online (Sandbox Code Playgroud)

这适用于自定义标题,但对于我不想要任何标题的表格,它显示一个白色框.我想这return nil;会阻止为该表显示任何标题.这个假设是否正确?还有别的东西会覆盖吗?我怎么能这样做才能显示出来?

rma*_*ddy 12

每当实现该viewForHeaderInSection方法时,您还必须实现该heightForHeaderInSection方法.请确保返回0没有标题的部分的高度.

  • 如果你阅读`viewForHeaderInSection'的文档,你会看到:"当tableView:heightForHeaderInSection:`也被实现时,这个方法才能正常工作." (2认同)

Wil*_* Hu 5

如果您使用这种方式,则不需要计算高度。

tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 50
Run Code Online (Sandbox Code Playgroud)

如果您有空部分,您可以将高度设置为零,或者您不需要此方法。

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2 {
            return 0
        }
        return UITableView.automaticDimension
    }
Run Code Online (Sandbox Code Playgroud)