Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
    }
}
like image 342
JimmyJammed Avatar asked Jul 20 '16 16:07

JimmyJammed


1 Answers

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)];
like image 168
JimmyJammed Avatar answered Sep 24 '22 21:09

JimmyJammed