Search code examples
iphoneiosuitableviewios5

UITableView: custom header title view doesn't show


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.


Solution

  • I seem to have found a solution:

    I have created a lazy loading strong property for each header view I want to display. (luckily there are only three)

    Now the views are shown.

    It seems that the header views got deallocated without the strong references before the table was rendered.

    Could it be that there is a connection to the class implementing the table view delegate and data source protocols is not a UIViewController?