Ios – UITableView: custom header title view doesn’t show

iosios5iphoneuitableview

I want to display a table with custom header titles.
The table view is attached to a controller class that implements the tableview delegate and data source protocols but is not a subclass of UIViewController because the table is a subview to be displayed above another tableview.

some snippets of my code:
The tableview is created programmatically:

    _myListView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStyleGrouped];

[_myListView setDataSource:self.myListController];
[_myListView setDelegate:self.myListController];
[_myListView setBackgroundColor:darkBackgroundColor];

where myListController is a strong property in the class.

For the number of rows in sections:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    …
    return count;    
}

The number of sections:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [someDelegate sectionCount];
}

For the custom Header View:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, SectionHeaderHeight)];
    UILabel* sectionHeaderTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 3, 300, 24)];

    [headerView setBackgroundColor:[UIColor clearColor]];

    sectionHeaderTitle.text = [self myTitleForHeaderInSection:section];
    sectionHeaderTitle.textColor = [UIColor whiteColor];
    sectionHeaderTitle.textAlignment = UITextAlignmentLeft;

   [headerView addSubview:sectionHeaderTitle];

    return headerView;
}

For the custom headerViewHeight (as required since iOS5):

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ( [self tableView:tableView numberOfRowsInSection:section] > 0) {
        return SectionHeaderHeight;
    } else {
        return 0;
    }
}

Sadly, the tableview does not display any section headers just as if I would return nil.
However, I have checked with a breakpoint, that the code actually returns an UIView.

Everything else works fine.

What am I missing? PLease, don't hesitate to make me feel ashamed of my self.

Best Answer

I don't really understand why you want to use a custom view, and not the "standard" one ? You may have your reasons, but I don't see anything in your code telling me why :)

I would personally just use this:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) return @"First section header title";
    if (section == 1) return @"Second section header title";
    else return nil;
}

Tell me if that's not what you're looking for !

Related Topic