swift - uitableview教學 - tableview xcode
使用動態類型時調整表頭的大小 (2)
我有一個帶有標題的TableViewController
。 這個頭是一個容器,它鏈接到另一個名為Header.storyboard
故事板
Header.storyboard
包含一些帶有一些標籤的動態類型的堆棧視圖。
標籤文本來自DB。
沒有問題的文字尺寸或大小,我想正確形象化。
我已經使用了一些答案來正確調整標題的大小,但沒有運氣:
import UIKit
class TableViewController: UITableViewController {
@IBOutlet weak var tableHeaderView: UIView!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Dynamic sizing for the header view
if let headerView = tableHeaderView {
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
var headerFrame = headerView.frame
// If we don't have this check, viewDidLayoutSubviews() will get
// repeatedly, causing the app to hang.
if height != headerFrame.size.height {
headerFrame.size.height = height
headerView.frame = headerFrame
tableHeaderView = headerView
}
}
}
}
嘗試實施
tableView(_ tableView: UITableView, heightForHeaderInSection section: Int)
和
tableView(_ tableView: UITableView, viewForHeaderInSection section: Int)
你的代碼應該是這樣的:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableHeaderView.bounds.size.height
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableHeaderView
}
表視圖標題可以自動調整大小
但與容器,它可能不會工作
使用自定義視圖,而不是viewForHeaderInSection
class ViewController: UITableViewController {
override func viewDidLoad() {
tableView.estimatedSectionHeaderHeight = 10
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let lab = UILabel()
lab.text = "text \(section)"
lab.font = UIFont.systemFont(ofSize: 10 * CGFloat(section) + 1)
return lab
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
//this method overriding is not necessary
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
}