一般来说,在表格视图单元格中嵌入表格视图是一个糟糕的设计,原因有很多。
- 表格视图没有固有的高度...所以无论您添加多少单元格,它都不会设置自己的高度。有办法解决这个问题,但是...
- 根据单元格数量更改表格视图的高度会破坏“可重用”单元格设计。表视图将其用于内存管理。
- 您最终会滚动单元格的内容,而包含该单元格的表格视图也想要滚动。
- 每个表格视图都需要一个单独的
dataSource 和 delegate 类。
除非您的设计比您展示的要复杂得多,或者您有其他令人信服的理由将表格视图嵌入到单元格中,否则您将使用这种方法会更好:
- 一个表格视图
- 两个细胞类别 - 我将它们称为白色和红色以匹配您的图像
- 一个
dataSource - 如果indexPath.row == 0 则返回WhiteCell,其余行返回RedCell。
以下是该方法的概述:
class WhiteCell: UITableViewCell {
func configureCell(_ strings: [String]) -> Void {
// configure the labels for this cell
}
}
class RedCell: UITableViewCell {
func configureCell(_ strings: [String]) -> Void {
// configure the labels for this cell
}
}
class MyTableViewController: UITableViewController {
let whiteData: [String] = [
"Line 1",
"Line 2",
"Line 3",
"Line 4",
// etc...
]
let redData: [[String]] = [
[ "A string 1", "A string 2", "A string 3", ],
[ "B string 1", "B string 2", "B string 3", ],
[ "C string 1", "C string 2", "C string 3", ],
[ "D string 1", "D string 2", "D string 3", ],
// etc...
]
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// number of red rows + the white row
return redData.count + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "WhiteCell", for: indexPath) as! WhiteCell
cell.configureCell(whiteData)
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "RedCell", for: indexPath) as! RedCell
// because the red cells start at .row == 1, and the data array is zero-based,
// we use [indexPath.row - 1]
cell.configureCell(redData[indexPath.row - 1])
return cell
}
}