Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 328
DBoyer Avatar asked Jan 13 '14 07:01

DBoyer


2 Answers

-(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;
}
like image 67
Zeeshan Avatar answered Oct 24 '22 04:10

Zeeshan


You can just

return UITableViewAutomaticDimension;

EDIT: Oops, ignore the following, see comments below.

or

return UITableViewAutomaticDimension + padding;
like image 21
guywithmazda Avatar answered Oct 24 '22 05:10

guywithmazda