objective-c - 从 XIB 加载 viewForSectionHeader 时遇到问题

标签 objective-c ios uitableview ios5

我真的很想通过使用 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/

相关文章:

objective-c - 用于呈现多个模态的 NSNotificationCenter?

objective-c - 在 Cocoa/Cocoa Touch 中,有没有办法在运行时动态确定类的 ivars?

ios - 从普通 AR View 切换到耳机 AR View

ios - 在标签中显示百分比

ios - 如何滚动到 UITableView 或 UICollectionView 中的最后一个单元格之外

ios - UITextView - 最大换行符

ios - 即使用户拒绝从 App 访问 Twitter,也会出现 Twitter 登录页面

iOS 使用来自 UIWebVIew 的外部应用程序打开文档

ios - 为什么 UITableViewCell 不可访问(对于 VoiceOver)

iphone - UITableView 插入更多行,同时保留已经获取的行