3

我似乎无法使用 Storyboard 向 UITableView 添加标题。我有一个 UITableView ,其中有一些原型单元格正在显示并且工作正常。然后,我在这些原型单元格上方拖动了一个新的 UIView 并向其添加了一个标签以充当我的表格的标题(而不是作为部分标题)。我创建了一个新的 UIView 子类,它只有一个属性,即 UILabel。故事板中 UIView 的类设置为这个自定义 UIView,而 UILabel 的引用出口设置为我自定义 UIView 类的 UILabel 属性。

然后,在我的 UITableViewController 的 viewDidLoad 方法中,我正在执行以下操作:

DetailTableHeaderView *headerView = [[DetailTableHeaderView alloc] init];
headerView.entryNameLabel.text = @"TEST";
self.tableView.tableHeaderView = headerView;
[self.tableView reloadData];

但是当我运行我的应用程序时,表头根本没有出现。我还注意到 headerView.entryNameLabel 的 text 属性甚至没有设置为应有的“TEST”。

我在这里做错了什么?

4

2 回答 2

2

Old question, but I am providing my answer for reference reasons since it's still a bit non trivial how to add a tableview header, using storyboard for the design part.

  1. Add a prototype cell in your tableview in your storyboard.
  2. Having your prototype cell selected, in the attributes inspector on your right, give it an identifier (ex headerViewCell), since this is how your will reference it in order to use it.
  3. Now click on the size inspector tab and give it a row height (this gonna be your header view height)
  4. In the code now, in the controller that handles the tableview:

    - (void)viewDidLoad {
        [super viewDidLoad];
        self.tableView.tableHeaderView = [self.tableView dequeueReusableCellWithIdentifier:@"headerViewCell"];
    }
    
于 2015-11-13T14:46:09.693 回答
-1

这个问题已经很老了,但写下这个答案,希望这会对某人有所帮助。

处理表 headerView 的好方法是使用委托方法。实现tableView:viewForHeaderInSectiontableView:heightForHeaderInSection委托方法。tableView:viewForHeaderInSection从方法返回你的 UIView 。

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

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
}

另一种选择是使用原型单元格(自定义单元格)作为标题视图并在 tableView:viewForHeaderInSection 方法中返回它。请参见下面的代码(我没有测试过这个):

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

    HeaderView *headerView = [self.TableView dequeueReusableHeaderFooterViewWithIdentifier:@"tableHeader"];

    // Set Text
    headerView.headerLabel.text = @"Some title";

    return headerView.contentView;
}

更新

以上也适用于 tableView:viewForHeaderInSection: 方法。这是示例代码:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewCell *sectionHeader;
    CustomSectionHeaderCell *sectionHeaderCell = [tableView dequeueReusableCellWithIdentifier:@"sectionHeaderCell"];

    // do stuff here

    return sectionHeaderCell.contentView;
}
于 2013-12-12T19:36:47.933 回答