This example shows a table with two sections: "Fruits" and "Vegetables". Each section has a header title and a footer note. The table displays the items in each group.
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
let tableView = UITableView()
let data = [["Apple", "Banana"], ["Carrot", "Lettuce"]]
let headers = ["Fruits", "Vegetables"]
let footers = ["End of fruits", "End of vegetables"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.dataSource = self
view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = data[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return footers[section]
}
}