我找到了通過設定在 UITableView 中獲取動態標題高度的解決方案
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
我得到的效果是標題設定為一個 UILabel 行的高度,而它應該設定為所有行的高度。我在 Horizo??ntalStackView 中有兩個 UILabel。當 UILabel 之一超過一條線時,自動高度調整不起作用。我試過設定
tableView.beginUpdates()
tableView.endUpdates()
在某些開始方法中,但沒有任何效果。
uj5u.com熱心網友回復:
UILabel第 1 步:計算方法中兩個文本的高度heightForHeaderInSection。
第 2 步:回傳 中的最大高度heightForHeaderInSection。
并確保將UILabel'numberOfLines屬性設定為 0。
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let font = UIFont.systemFont(ofSize: 23)
let height1 = "section \(section) label1 text".height(withConstrainedWidth: UIScreen.main.bounds.width/2 , font: font)
let height2 = "section \(section) label2 text".height(withConstrainedWidth: UIScreen.main.bounds.width/2 , font: font)
return max(height1,height2)
}
這里我使用擴展來計算文本String的高度。UILabel
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.height)
}
}
uj5u.com熱心網友回復:
假設您已經使用 XIB 檔案設定了 Section Header,這可能是一個約束問題,導致大小不正確等。
我匯總了使用動態節標題時可能發生的常見錯誤串列。請一一檢查,看看哪一個可以解決您的問題。
1. 確保您的約束設定正確。
打開 Section Header XIB 并確保有足夠的約束UITableView來計算視圖的高度。請注意,我已經設定了優先級為 999 的底部約束。這很重要,因為第 3 步。
2.確保你UILabel能成長
將兩個UILabels 的“行數”設定為零,如下所示。
3.調整內容的擁抱和抗壓性
選擇您的 UILabel,然后單擊“Size Inspector”(
)。
在底部,將這些值設定為 1000,以便自動布局將它們視為與其他約束一樣重要。
- 內容擁抱優先級 > 垂直
這設定了UILabel' 的高度應該如何擁抱其文本內容。
- 抗壓優先>垂直
這設定了UILabel應該抵抗將其高度縮小到其內容高度之外的程度。
像這樣:
4.回傳一個合理的值 estimatedHeightForHeaderInSection
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return 44.0
}
5.編譯運行!
您的部分標題現在應該正確調整大小。
筆記:
確保您的資料源不是不依賴于部分索引的隨機文本。
如果您的部分標題重疊或大小不正確,請確保您的資料源在
UITableView滾動時沒有更改。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/415988.html
標籤:
上一篇:如何使用來自LaravelAPI的專案填充此Vue選擇?
下一篇:如何保存django表單
