【发布时间】:2019-07-12 23:45:26
【问题描述】:
我有一个带有标题的表格视图 (1)。我想在该标题中放置另一个表格视图 (2)。问题是第二个表格视图的单元格是动态的,所以我需要确保第一个表格视图的标题也是动态的。
我已按照本教程使第一个表格视图的标题动态化:
https://useyourloaf.com/blog/variable-height-table-view-header/
但是当我运行模拟器时表格视图标题甚至没有显示,我相信这与第二个表格视图的单元格是动态的这一事实有关,因此没有为第一个表格视图的标题分配高度.
所以我的问题是,是什么导致标题不显示,我该如何解决?
这是我的代码:
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var firstTableView: UITableView!
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var secondTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
firstTableView.delegate = self
firstTableView.dataSource = self
secondTableView.delegate = self
secondTableView.dataSource = self
// Make the first table view's cells dynamic
firstTableView.rowHeight = UITableView.automaticDimension
firstTableView.estimatedRowHeight = 50
// Make the second table view's cells dynamic
secondTableView.rowHeight = UITableView.automaticDimension
secondTableView.estimatedRowHeight = 50
// Register the custom xib for the first table view
firstTableView.register(UINib(nibName: "FirstTableViewCell", bundle: nil), forCellReuseIdentifier: "FirstTableViewCell")
// Register the custom xib for the second table view
secondTableView.register(UINib(nibName: "SecondTableViewCell", bundle: nil), forCellReuseIdentifier: "SecondTableViewCell")
}
/**
Used to resize the table view header.
Source: https://useyourloaf.com/blog/variable-height-table-view-header/
*/
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let headerView = firstTableView.tableHeaderView else {
return
}
let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
if (headerView.frame.size.height != size.height) {
headerView.frame.size.height = size.height
firstTableView.tableHeaderView = headerView
firstTableView.layoutIfNeeded()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.firstTableView {
return 100
}
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.firstTableView {
// Logic to create new cell
} else if tableView == self.secondTableView {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SecondTableViewCell", for: indexPath) as? SecondTableViewCell else {
fatalError("The dequeued cell is not an instance of SecondTableViewCell.")
}
cell.initialize()
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
【问题讨论】:
-
我认为你应该重新考虑你的布局,因为将 tableView 放在 tableView 的标题中会很奇怪和令人沮丧
-
在表格视图的标题中需要表格视图的原因是什么?
-
我想在第一个表视图上方显示几个其他视图,我的第一个想法是实现一个标题。有什么更好的方法?我想将其他 3 个视图放在第一个表视图上方,但我也希望它们一起滚动。
-
您只想制作 1 个包含 2 个部分的表格视图。您可以在不同部分进行不同的设置,而不会出现任何问题。
标签: ios swift uitableview tableview swift4