简体   繁体   中英

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.

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;
}

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.

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;

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM