无法从XIB加载viewForSectionHeader

时间:2012-06-13 01:45:33

标签: objective-c ios uitableview ios5

我真的希望通过使用Interface Builder在XIB中进行布局来完全控制节标题。

我正在使用下面的代码,但是当我运行应用程序时,我的titleLabel.text没有改变。它继续显示每个节标题的默认“标签”文本。我已经NSLog了headerText的值,它确实包含正确的字符串。

有什么想法吗?谢谢

- (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;
}

更新答案: 这是我在阅读Tammo的答案后如何运作

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;

1 个答案:

答案 0 :(得分:1)

免责声明:我不认为拥有这种观点的控制器是正确的做法。

您的代码存在的问题是控制器仅在需要时才加载视图。访问titleLabel时,视图尚未加载,因此titleLabel为nil。尝试

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

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

cshvc.titleLabel.text = headerText;

return result;
相关问题