UITableViewController select header for section

No there is no way to do it with the UITableViewDelegate.

What you can do is to add a button the size of the section header view and add it to the view. Set the tag of the button to the section index. Then just add the UIViewController as a target for the UIControlEventTouchUpInside.

Then by looking at the tag of the button you can see which section is clicked.


This isn't radically different than @rckoenes answer, but it does provide a more orthodox way of handling events on views rather than using invisible buttons.

I'd rather add a UITapGestureRecognizer to my header view instead of adding invisible buttons and resizing them:

UITapGestureRecognizer *singleTapRecogniser = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease];
[singleTapRecogniser setDelegate:self];
singleTapRecogniser.numberOfTouchesRequired = 1;
singleTapRecogniser.numberOfTapsRequired = 1;   
[yourHeaderView addGestureRecognizer:singleTapRecogniser];

and then:

- (void) handleGesture:(UIGestureRecognizer *)gestureRecognizer;

You can use gesture.view to see which was touched. Then do whatever you need to do to find out which header it was (tags, data array lookup... )


Here is what worked for me in Swift 2:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let footerView = UITableViewHeaderFooterView()
    footerView.textLabel?.text = "Header Text"
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
    tapRecognizer.delegate = self
    tapRecognizer.numberOfTapsRequired = 1
    tapRecognizer.numberOfTouchesRequired = 1
    footerView.addGestureRecognizer(tapRecognizer)
    return footerView
}

@objc func handleTap(gestureRecognizer: UIGestureRecognizer) {
    print("Tapped")
}