我真的很想通过使用 Interface Builder 在 XIB 中布局来完全控制节标题。
我正在使用下面的代码,但是当我运行应用程序时,我的 titleLabel.text 没有改变。它继续显示每个节标题的默认“标签”文本。我已经对 headerText 的值进行了 NSLog 处理,它确实包含正确的字符串。
有什么想法吗?谢谢
- (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;
最佳答案
免责声明:我不认为为这种 View 提供 Controller 是正确的做法。
您的代码的问题是 Controller 仅在需要时加载 View 。访问titleLabel时, View 尚未加载,因此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;
关于objective-c - 从 XIB 加载 viewForSectionHeader 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11007183/