您似乎没有设置dataSource或tableView委托(除非它发生在未显示的代码的某些部分)。这(以及大多数动态tableview函数)都需要这些。
对于不会改变大小的页眉/页脚,创建它们相当简单-返回要从中使用的视图
tableView(_:viewForHeaderInSection:)
你想要的高度
tableView(_:heightForHeaderInSection:)
. 将它们分别设置为nil和0以隐藏头。
一个简单的示例,它为0&2节提供不同大小的页眉,为1节提供无页眉,并隐藏所有页脚。我已经设置了标题的背景颜色,使其突出,而没有提供其他方法,如
cellForRowAt
. 注意,高度由高度方法控制,而不是框架高度。
class MyVC1: UIViewController {
var mapa: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
title = "Dummy TableView"
view.backgroundColor = .lightGray
let tableView = UITableView(frame: CGRect(x:50, y:100, width: 300, height: 680), style: .grouped)
view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.dataSource = self
tableView.delegate = self
}
}
//add dataSource and delegate support
extension MyVC1: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
5
}
func numberOfSections(in tableView: UITableView) -> Int {
3
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
let v = UIView(frame: CGRect(x: 10, y: 10, width: tableView.frame.width - 20, height: 90))
v.backgroundColor = .purple
return v
case 1: return nil
case 2:
let v = UIView(frame: CGRect(x: 10, y: 10, width: tableView.frame.width - 20, height: 20))
v.backgroundColor = .magenta
return v
default: fatalError()
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0: return CGFloat(60)
case 1: return CGFloat(0)
case 2: return CGFloat(100)
default: fatalError()
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
nil
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
0
}
}