Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 333
iDia Avatar asked Apr 15 '13 11:04

iDia


2 Answers

You can get the header view for selected Index like :

UIView *headerView=[deviceTable headerViewForSection:indexPath.section];

Then get the child from the headerView by looping through.like

for(UIView *view in headerView.subviews)
{
     if ([v isKindOfClass:[UILabel class]])
        {
            UILabel *label=(UILabel *)v;
            NSString *text=label.text;
        }
}

Edit: As Desdenova suggested :

    UITableViewHeaderFooterView *headerView=[deviceTable headerViewForSection:indexPath.section];
    NSString *title=headerView.textLabel.text;
like image 61
V-Xtreme Avatar answered Sep 17 '22 21:09

V-Xtreme


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];
}
like image 34
jszumski Avatar answered Sep 17 '22 21:09

jszumski