[英]Height of UITableViewHeaderFooterView
如何在-tableview:heightForFooterInSection:
计算UITableViewHeaderFooterView
的高度-tableview:heightForFooterInSection:
? 我提前创建了视图,它包含textLabel
中的动态文本,因此具有不同的高度。
基于我使用以下的其他答案,我对这个解决方案并不完全满意,因为它使用了硬编码的填充,并没有考虑detailTextLabel
,但它适用于我的情况。
- (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;
}
使用boundingRectWithSize:options:attributes:context:计算textLabel的高度。 然后你就可以获得页脚视图的高度。
如果更改textLabel的文本,请记住重新加载tableView。
其他方式:
textLabel.bounds = CGRectMake(0, 0, maxWidth, maxHeight);
[textLabel sizeToFit];
然后你的textLabel的高度将是正确的。
正如@Harrison Xi所指出的,你可以使用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;
这是@ Nick在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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.