// Using a UITableViewController
class SecHeadTVC: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Section Header TableViewController"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "c")
if #available(iOS 15.0, *) {
tableView.sectionHeaderTopPadding = 0.0
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath)
c.textLabel?.text = "\(indexPath)"
c.textLabel?.backgroundColor = .cyan
c.contentView.backgroundColor = .yellow
return c
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = UILabel()
v.text = "Header for section: \(section)"
v.backgroundColor = .green
return v
}
}
// Using a UITableView as a Subview of a UIViewController
class SecHeadVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Section Header TableView as Subview"
view.backgroundColor = .systemYellow
let tv = UITableView()
tv.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tv)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
tv.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
tv.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
tv.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
tv.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
])
tv.register(UITableViewCell.self, forCellReuseIdentifier: "c")
tv.dataSource = self
tv.delegate = self
if #available(iOS 15.0, *) {
tv.sectionHeaderTopPadding = 0.0
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath)
c.textLabel?.text = "\(indexPath)"
c.textLabel?.backgroundColor = .cyan
c.contentView.backgroundColor = .yellow
return c
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = UILabel()
v.text = "Header for section: \(section)"
v.backgroundColor = .green
return v
}
}
Comments
0 B
|👍
/👎
0 B
|👍
/👎
0 B
|👍
/👎