Nick
Nick

Reputation: 4248

Height of UITableViewHeaderFooterView

How can I calculate the height of a UITableViewHeaderFooterView in -tableview:heightForFooterInSection:? I create the view ahead of time, and it contains dynamic text in the textLabel so has a varying height.

Upvotes: 3

Views: 1721

Answers (4)

Alan Kinnaman
Alan Kinnaman

Reputation: 927

Here's a version of @Nick's answer in Swift 3:

func heightOfHeaderFooterView(view: UITableViewHeaderFooterView) -> CGFloat {
    if let text = view.textLabel?.text as NSString? {
        let size = CGSize(width: tableView.bounds.size.width - 2 * tableView.separatorInset.left, height: CGFloat.greatestFiniteMagnitude)
        let rect = text.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSFontAttributeName : (view.textLabel)!.font], context: nil)
        return rect.size.height + 20
    }
    return 0
}

Upvotes: 0

Nick
Nick

Reputation: 4248

Based on the other answers I used the following, I'm not entirely happy with this solution as it uses a hardcoded padding and it doesn't account for the detailTextLabel, but it works in my case.

- (CGFloat)heightOfHeaderFooterView:(UITableViewHeaderFooterView *)view {
    return ceilf([view.textLabel.text boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width - 2*self.tableView.separatorInset.left, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:view.textLabel.font} context:nil].size.height) + 20;
}

Upvotes: 3

Sreejith
Sreejith

Reputation: 1355

As @Harrison Xi pointed out, you can use boundingRectWithSize:options:attributes:context:

CGRect headerFrame = [YOUR_STRING boundingRectWithSize:CGSizeMake(240.f, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"" size:15.0f]} context:nil];

CGSize requiredSize = headerFrame.size;

return requiredSize.height;

Upvotes: 1

Harrison Xi
Harrison Xi

Reputation: 796

Use boundingRectWithSize:options:attributes:context: to calculate the height of your textLabel. Then you will be able to get the height of footer view.

If you change the text of your textLabel, remember to reload your tableView.

Another way:

textLabel.bounds = CGRectMake(0, 0, maxWidth, maxHeight);
[textLabel sizeToFit];

Then your textLabel's height will be correct.

Upvotes: 1

Related Questions