DBoyer DBoyer - 6 months ago 42
iOS Question

Header/Footer height of a UITableView section based on title text height

I am wondering if its possible to make the height header/footer for a section of a UITableView be equal to the height of the header/footer title text. Any tips would be great!

Note: some sections of my TableView may not have a header/footer and in that case would just have the padding between sections since the "headerTitleHeight/footerTitleHeight" would be zero in this case.

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return headerTitleHeight + padding;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return footerTitleHeight + padding;
}

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

    NSString *myHeader = [sectionsArray objectAtIndex:section];
    CGSize maxSize = CGSizeMake(320, 999999.0);
    int height = 0;

    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          font, NSFontAttributeName,
                                          nil];

    if (IS_IOS_6) //Macro i made for if iOS 6
    {
        CGSize size = [myHeader sizeWithFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:(15)]
                             constrainedToSize:maxSize
                                 lineBreakMode:NSLineBreakByWordWrapping];
        height = size.height;
    }
    else // IOS 7 , Attributes
    {
        CGRect frame = [myHeader boundingRectWithSize:maxSize
                                                options:NSStringDrawingUsesLineFragmentOrigin
                                             attributes:attributesDictionary
                                                context:nil];
        height = frame.size.height;
    }

    return height+5;
}
Comments