UITableView tableFooterView shows at the top of the UITableView - wrong

sudoExclaimationExclaimation picture sudoExclaimationExclaimation · Sep 25, 2017 · Viewed 10k times · Source

I have created a very simple test case to reproduce this issue.

I am trying to set a footer view programmatically to a tableview. Please note that I am referring to the footer at the very bottom of the tableview - NOT the section footer (most stack overflow answers confuse them).

Here's my very simple code:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *footerContainer = [[UIView alloc] initWithFrame:CGRectZero];
    footerContainer.backgroundColor=[UIColor greenColor];
    footerContainer.translatesAutoresizingMaskIntoConstraints=NO;
    [footerContainer addConstraints:@[[NSLayoutConstraint
                                       constraintWithItem:footerContainer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual
                                       toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:100
                                       ],
                                      [NSLayoutConstraint
                                       constraintWithItem:footerContainer attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual
                                       toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:[UIScreen mainScreen].bounds.size.width
                                       ]]];

    self.mytableview.tableFooterView=footerContainer;
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text=[NSString stringWithFormat:@"%ld",indexPath.row];
    return cell;
}

However, the outcome looks like this:

enter image description here

As you notice, the footer shows on top of the tableview. Is this a bug or am I missing something?

If I change the tableFooterView to tableHeaderView, then it works fine. So I was expecting the same to work for footer too but it doesn't.

Answer

gohnjanotis picture gohnjanotis · May 13, 2018

Do not set translatesAutoresizingMaskIntoConstraints = false on a UIView being assigned to tableView.tableFooterView.

In your case, this is footerContainer. I had this same problem. It was mentioned in a comment on the question, but I still spent hours troubleshooting before I noticed I was doing that, so I am putting it here as a possible answer as well.