How to get the section header view's title when selecting a Cell

cocoa-touch, ios, uitableview

Solution

I would suggest implementing both `tableView:titleForHeaderInSection:` and `tableView:viewForHeaderInSection:` (if both are implemented then iOS prefers `viewForHeaderInSection:`). Then have your implementation of `tableView:viewForHeaderInSection:` create its view with the label and populate it with the result of `tableView:titleForHeaderInSection:`:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
     UIView *yourHeaderView;
     UILabel *someLabel;

     // set up the view + label

     // if self doesn't implement UITableViewDelegate, you can use tableView.delegate
     someLabel.text = [self tableView:tableView titleForHeaderInSection:section];

     return yourHeaderView;
}

Now when you're responding to a row tap, it's very easy to get the corresponding title:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     NSString *titleForHeader = [self tableView:tableView titleForHeaderInSection:indexPath.section];
}

Problem

I have an `UITableView` which has many `sections`, and each section has only 1 row. What I want to do is that, when I click on a particular cell, the title of the header that corresponds to the cell should be changed. I have set the section header using `-tableView:viewForHeaderInSection:` How can I get the row header title inside the `-tableView:didSelectRowAtIndexPath:` method?

Original source