UITableview Section标题不显示文本

C.J*_*hns 1 iphone uitableview ios

我已将此代码添加到我的UITableViewController以返回灰色标题部分.

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
   [headerView setBackgroundColor:[UIColor grayColor]];
    return headerView;
}
Run Code Online (Sandbox Code Playgroud)

但是现在这样做我看不到标题字符...我需要将其添加为子视图吗?还是有另一种做事方式?

我有这些方法将标题和标题文本添加到UITablView但是当我使用上面的方法时,我再也看不到它们了.

// Section headers
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{    
    return [sectionLetterArray objectAtIndex:section];
}

// Section header titles
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return sectionLetterArray;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 7

如果你创建自己的tableView:viewForHeaderInSection,你必须创建UILabel或其他,并自己填写文本,例如:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    [headerView setBackgroundColor:[UIColor grayColor]];

    // Add the label
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(kSectionTitleLeftMargin, 
                                                                     kSectionTitleTopMargin, 
                                                                     tableView.bounds.size.width - kSectionTitleLeftMargin - kSectionTitleRightMargin, 
                                                                     30.0 - kSectionTitleTopMargin - kSectionTitleBottomMargin)];

    // do whatever headerLabel configuration you want here

    headerLabel.text = [self tableView:tableView titleForHeaderInSection:section];
    [headerView addSubview:headerLabel];

    // Return the headerView
    return headerView;
}
Run Code Online (Sandbox Code Playgroud)

显然,无论如何都要更改headerLabel,但关键的实用信息是,如果您创建自己的视图,则必须自己创建标签并填写文本.