Question

I have implemented custom header section for UITableView. There is a button into the customised view of Header and I want to get the index of that section on tapping action of that button.

I may try by going as

CustomHeader *view = (CustomHeader*)btnObject.superView;

But from this headerView's Instance how can i get the IndexPath or index of that Section?

EDIT: I need something that is independent on tag or any thing just similar to the indexpath for Cell as below

-(NSIndexPath*)indexPathFromSenderView:(UIView*)view{

    CGPoint center= view.center;
    CGPoint rootViewPoint = [view.superview convertPoint:center toView:self.tblMainContainer];
    NSIndexPath *indexPath = [self.tblMainContainer indexPathForRowAtPoint:rootViewPoint];
    return indexPath;
}
Was it helpful?

Solution

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

    // create custom header here

    // set up a button method
    [yourButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

    // set the button tag as section
    yourButton.tag = section;

    return yourCustomHeaderWithButton;
}


later


-(void)buttonAction:(id)sender{

    UIButton *clickedButton = (UIButton*)sender;
    NSLog(@"section : %i",clickedButton.tag);

}

OTHER TIPS

You need to use the tag. There's no way to get the indexPath from a header section unlike a normal cell. If you want, you can make the header section view into a UITableViewCell row instead and just add it as the top row in your section.

BTW you can use

[self.tableView indexPathForCell:cell]

instead to get the index path for a cell.

If you decide to use a tag, you can update the tag value by using the following code in your action method:

[UIView animateWithDuration:0.2 animations:^{
        [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionToDelete] withRowAnimation:UITableViewRowAnimationAutomatic];
    } completion:^(BOOL finished){
        [self.tableView reloadData];
    }];

This will prevent the tag value from being wrong and stop your application from crashing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top