How to add touch events to a UITableViewFooter (or header)

Table View headers or footers can’t be tapped. Sometimes however that’s exactly what we want to do.

In this example we’ll add a new UIView to out table view and add it to the table’s footer. Inside this view we’ll have a custom button which we’ll create with an image. We’ll also have a method that is called when the user presses the button:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    // height of the footer
    // this needs to be set, otherwise the height is zero and no footer will show
    return 80;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    // creates a custom view inside the footer
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 80)];

    // create a button with image and add it to the view
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 320, 78)];
    [button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(footerTapped) forControlEvents:UIControlEventTouchUpInside];

    [footerView addSubview:button];

    return footerView;
}

- (void)footerTapped {

    NSLog(@"You've tapped the footer!");
}

The result is a row at the bottom of the table view which stays in place even if the table is scrolled – ideal of anything users should see at all times.

You can do the same for table view headers, just add the code to the “headerInSeaction” variants of the methods above.

Example of a tappable footer image/button
Example of a tappable footer image/button




2 thoughts on “How to add touch events to a UITableViewFooter (or header)

    1. Hi Joan, that’s not correct: the viewForFooterInSection method is called exactly once, not multiple times – hence the button is created only once. Try it out with a simple log message.

      Alternatively, you can create reference to the button (or in fact the footer view) with a custom initialiser and simply call that in viewForFooterInSection. Or you can tag your view and ask if it exists before creating it again – just in case you’re worried.

      And perhaps next time, rather than simply expressing a dislike in an article, offer some advice to us all on how to make it better.

Leave a Reply