iOS7 - Multiline Text in TableView Header?

10,438

Solution 1

This is how I do it, I got this multi line table header result:

Result

Multiline Table Header

Source Code

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.dataSource = @[@"apple", @"banana", @"orange", @"grapes", @"watermelon"];
    self.sectionNames = @[
                          @"Fixture Counts per \nTable 2902.1 - 2014 IBC\n\n    Occupancy Recap",
                          @"Women Fixtures",
                          @"Mens Fixture",
                          @"General Fixtures",
                          ];

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame];
    tableView.delegate = self;
    tableView.dataSource = self;

    [self.view addSubview:tableView];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionNames.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return self.dataSource.count;
    }
    else
    {
        return 0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    cell.textLabel.text = [self.dataSource objectAtIndex:indexPath.row];

    return cell;
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // calculate height of UILabel
    UILabel *lblSectionName = [[UILabel alloc] init];
    lblSectionName.text = [self.sectionNames objectAtIndex:section];
    lblSectionName.textColor = [UIColor lightGrayColor];
    lblSectionName.numberOfLines = 0;
    lblSectionName.lineBreakMode = NSLineBreakByWordWrapping;
    lblSectionName.backgroundColor = [UIColor grayColor];

    [lblSectionName sizeToFit];

    return lblSectionName.frame.size.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // calculate height of UILabel
    UILabel *lblSectionName = [[UILabel alloc] init];
    lblSectionName.text = [self.sectionNames objectAtIndex:section];
    lblSectionName.textColor = [UIColor lightGrayColor];
    lblSectionName.numberOfLines = 0;
    lblSectionName.lineBreakMode = NSLineBreakByWordWrapping;
    lblSectionName.backgroundColor = [UIColor grayColor];

    [lblSectionName sizeToFit];

    return lblSectionName;
}

Solution 2

Set TableView to display Static Cells under "Content" and pick Grouped under "Style".

Then you can have multi line headers and footers automatically.

Solution 3

In case anyone has a similar issue, here is my code for the tableview portion of the code, complete with the section I commented out:

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 4;
}


// Set Custom Heights for Headers
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if(section == 0 )
    return 100.0f;
else return 60.0f;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section)
{
    case 0: // Recap
        return 2;
        break;
    case 1: // Womens
        return 5;
        break;
    case 2: // Mens
        return 5;
        break;
    case 3: // General
        return 6;
        break;
}

return 0;
}

// ^.^ Customize the section title
//  -

/*
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{

switch (section)
{
    case 0:
        return [NSString stringWithFormat:@"Fixture Counts (rounded up) per \nTable 2902.1 - %@ IBC\n\n    Occupancy Recap", strCodeYear ];
        break;
    case 1:
        return [NSString stringWithFormat:@"Womens Fixtures"];
        break;
    case 2:
        return [NSString stringWithFormat:@"Mens Fixtures"];
        break;
    case 3:
        return [NSString stringWithFormat:@"General Fixtures"];
        break;
}
// To avoid "control reaches end of non-void function"
return 0;
}
*/


- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// calculate height of UILabel
UILabel *lblSectionName = [[UILabel alloc] init];
// lblSectionName.textColor = [UIColor lightGrayColor];
lblSectionName.numberOfLines = 0;
lblSectionName.lineBreakMode = NSLineBreakByWordWrapping;
lblSectionName.backgroundColor = [UIColor colorWithRed:245.0f/255.0f green:245.0f/255.0f blue:245.0f/255.0f alpha:0.9f];

// lblSectionName.text
switch (section)
{
    case 0:
        lblSectionName.text = [NSString stringWithFormat:@"Fixture Counts (rounded up) per \nTable 2902.1 - %@ IBC\n\n    Occupancy Recap", strCodeYear ];
        break;
    case 1:
        lblSectionName.text = [NSString stringWithFormat:@"Womens Fixtures"]; 
        break;
    case 2:
        lblSectionName.text = [NSString stringWithFormat:@"Mens Fixtures"]; 
        break;
    case 3:
        lblSectionName.text = [NSString stringWithFormat:@"General Fixtures"];
        break;
}

[lblSectionName sizeToFit];

return lblSectionName;
}

// ^.^ Customize the appearance of table view cells.
//  -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

// ^.^ Utilize the CustomCell class
//  -

static NSString *CustomCellIdentifier = @"CustomCellIdentifier";

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];

if (cell == nil)  {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    for (id oneObject in nib)
        if ([oneObject isKindOfClass:[CustomCell class]])
            cell = (CustomCell *)oneObject;
}

// Identify Section and Row
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];

// Sets the number of lines in the cell to be a variable
cell.titleLabel.numberOfLines = 0;

switch (section)
{
    case 0:
        cell.titleLabel.text = [titleFixOccupancyArray objectAtIndex:row];
        cell.dataLabel.text = [dataFixOccupancyArray objectAtIndex:row];
        cell.warningLabel.text = [warningFixOccupancyArray objectAtIndex:row];
        break;
    case 1:
        cell.titleLabel.text = [titleWomensArray objectAtIndex:row];
        cell.dataLabel.text = [dataWomensArray objectAtIndex:row];
        cell.warningLabel.text = [warningWomensArray objectAtIndex:row];
        break;
    case 2:
        cell.titleLabel.text = [titleMensArray objectAtIndex:row];
        cell.dataLabel.text = [dataMensArray objectAtIndex:row];
        cell.warningLabel.text = [warningMensArray objectAtIndex:row];
        break;
    case 3:
        cell.titleLabel.text = [titleFixturesArray objectAtIndex:row];
        cell.dataLabel.text = [dataFixturesArray objectAtIndex:row];
        cell.warningLabel.text = [warningFixturesArray objectAtIndex:row];
        break;  
}

return cell;
}

Solution 4

Following @Zhang, I prefer to use NSString boundRectWithSize to compute the header height:

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

    // create a custom multi-line label
    UILabel *label = [[UILabel alloc] init];
    label.text = self.headerText;
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = self.headerFont;
    [label sizeToFit];

    return label;
}

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

    // compute size
    NSString *text = self.headerText
    CGRect rect = [text boundingRectWithSize:CGSizeMake(CGRectGetWidth(tableView.frame), CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.headerFont} context:nil];

    return MAX(CGRectGetHeight(rect), 44); // keep height no smaller than Plain cells
}
Share:
10,438

Related videos on Youtube

Michael at AppsToKnow
Author by

Michael at AppsToKnow

Updated on September 15, 2022

Comments

  • Michael at AppsToKnow
    Michael at AppsToKnow over 1 year

    I am trying to update the code in one of my apps to iOS7 and I am transitioning it to using Storyboards. I have run into a snag in trying to get a table view header to display more than one line of text (the table view cells still work fine).

    The TableView was created using the Storyboard, but I am using the custom cell from the older program instead of building a new custom cell in the Storyboard.

    My code which used to work fine:

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    {
    
    switch (section)
    {
        case 0:
            return [NSString stringWithFormat:@"Fixture Counts per \nTable 2902.1 - %@ IBC\n\n    Occupancy Recap", strCodeYear ]; //(rounded up)
            break;
        case 1:
            return [NSString stringWithFormat:@"Womens Fixtures"];
            break;
        case 2:
            return [NSString stringWithFormat:@"Mens Fixtures"];
            break;
        case 3:
            return [NSString stringWithFormat:@"General Fixtures"];
            break;
    }
    // To avoid "control reaches end of non-void function"
    return 0;
    }
    

    The \n used to be enough to make the header expand with the text lines. I can tell that the \n is still triggering a return, but only one line of text is visible.

    I have resized the header to make sure there is enough room, but still only one line of text:

    // Set Custom Heights for Headers
    -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0 )
        return 200.0f;
    else return 60.0f; // put 22 in case of plain one..
    }
    

    I tried finding a way to use numberOfLines like for a label, but without success. I looked at the UITableView Class Reference and did not see anything referencing the number of lines, but I tried anyway:

    - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 2;
    return 0; // nil 0 view section
    }
    

    Any help is appreciated.

    • nhgrif
      nhgrif almost 10 years
      I'm surprised you're getting any text at all and no warning given your tableView:viewForHeaderInSection: method. You're returning nil when you should be returning a view...
  • Michael at AppsToKnow
    Michael at AppsToKnow almost 10 years
    Thank you - I was able to get it to work. I ended up commenting out titleForHeaderInSection and putting the switch in the viewForHeaderSection