[英]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.