iosuitableviewspacingtableheader

UITableView - Table Header View leaves spacing if view is removed


I have a UITableViewController that will display a table view header (NOT section header) if certain criteria is met. Displaying the controller with or without the header view on load works just fine. But if I show the header, then remove it, the spacing (where the header's frame was) remains at the top of the table view every time.

I have tried every combination of the following when removing the table view header with no luck:

[self.tableView beginUpdates];
self.tableView.tableHeaderView = nil;
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
[self.tableView reloadData];
[self.tableView endUpdates];

Anyone else encountered this?

Table View Header code:

- (void)updateTableHeaderView
{
    if (self.alerts.count && self.isViewLoaded) {
        [self.tableView beginUpdates];

        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), 40.0f)];
        headerView.preservesSuperviewLayoutMargins = YES;
        self.tableView.tableHeaderView = headerView;

        UIButton *alertButton = [UIButton buttonWithType:UIButtonTypeCustom];
        alertButton.tintColor = [UIColor whiteColor];
        alertButton.translatesAutoresizingMaskIntoConstraints = NO;
        [alertButton setBackgroundImage:[UIImage imageWithColor:alertTintColor] forState:UIControlStateNormal];
        [alertButton setBackgroundImage:[UIImage imageWithColor:alertHighlightedTintColor] forState:UIControlStateHighlighted];
        [alertButton addTarget:self action:@selector(alertButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:alertButton];

        NSDictionary *views = NSDictionaryOfVariableBindings(alertButton);
        NSDictionary *metrics = nil;

        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[alertButton]|" options:0 metrics:metrics views:views]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[alertButton]|" options:0 metrics:metrics views:views]];

        [self.tableView endUpdates];
    }
    else if (self.isViewLoaded) {
        [self.tableView beginUpdates];
        self.tableView.tableHeaderView = nil;
        [self.tableView endUpdates];
    }
}

Solution

  • It appears this is an iOS bug, and this is the current workaround for removing a tableHeaderView and it's spacing until fixed:

        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), 1.0f)];