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

- by

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



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.