Setting custom header view in UITableView

simonthumper picture simonthumper · Apr 30, 2013 · Viewed 11.7k times · Source

I am trying to add a custom view to the header of each of my UITableView's sections. I am using this delegate method to return the desired view. It is working partly as it causes the cell sections to be spread out as if there was a header there, however neither the text or UIButton actually appear. I know this method is being called as I places an NSLog in the method to see if it was. Am I making some kind of silly mistake, or is this not the right way of doing this?

 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        UIView* customView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, tableView.bounds.size.width, 44.0)];
        customView.backgroundColor = [UIColor clearColor];

        UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44.0)];
        headerLabel.textColor = [UIColor darkGrayColor];
        headerLabel.font = [UIFont boldSystemFontOfSize:16];


        UIButton *headerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        // add button to right corner of section

        return customView;
        switch (section) {
            case 0:
                headerLabel.text = @"Team Name";
                break;
            case 1:
                headerLabel.text = @"Captain";
                break;
            case 2:
                headerLabel.text = @"Wicket Keeper";
                break;
            case 3:
                headerLabel.text = @"Batting Order";
                headerButton.center = CGPointMake( 160.0, 22.0);
                headerButton.backgroundColor = [UIColor blueColor];
                headerButton.tag = section;
                [headerButton   addTarget:self action:@selector(enableCellReordering:) forControlEvents:UIControlEventTouchUpInside];
                [customView addSubview:headerButton];
                break;
            default:
                break;
        }

        [customView addSubview:headerLabel];
        return customView;
    }

Answer

Tom Redman picture Tom Redman · Apr 30, 2013

Found it, you return customView; before the switch statement.