sayguh
sayguh

Reputation: 2550

Trouble loading viewForSectionHeader from a XIB

I really want to have full control of section headers by laying out in a XIB using Interface Builder.

I'm using the code below, but my titleLabel.text is not changing when I run the app. It continues to show the default "Label" text for each section header. I've NSLog'd the value of headerText and it does contain the proper string.

Any ideas? Thank you

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

    CustomSectionHeaderViewController *cshvc = [[CustomSectionHeaderViewController alloc] initWithNibName:@"CustomSectionHeaderViewController" bundle:nil]; 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];

    NSString *headerText = [NSString stringWithFormat:@"%@", [sectionInfo name]];

    cshvc.titleLabel.text = headerText;

    return cshvc.view;
}

UPDATED WITH ANSWER: Here's how I got it working after reading Tammo's answer

CustomSectionHeader *cshv = [[[NSBundle mainBundle] loadNibNamed:@"CustomSectionHeader" owner:self options:nil]objectAtIndex:0];

   id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];

NSString *headerText = [NSString stringWithFormat:@"%@", [sectionInfo name]];

cshv.textLabel.text = headerText;


return cshv;

Upvotes: 0

Views: 132

Answers (1)

Tammo Freese
Tammo Freese

Reputation: 10754

Disclaimer: I don't think having a controller for that kind of view is the right thing to do.

The problem with your code is that the controller loads the view only when needed. When accessing titleLabel, the view is not loaded yet, so titleLabel is nil. Try

NSString *headerText = [NSString stringWithFormat:@"%@", [sectionInfo name]];

// Make sure that the view is loaded
UIView *result = [cshvc view];

cshvc.titleLabel.text = headerText;

return result;

Upvotes: 1

Related Questions