先日、セクションのようにUITableViewにもヘッダーとフッターがあることを知ったのでその方法をメモ。
1. Storyboardでヘッダーとフッター用のUITableViewCellを用意

2. ViewControllerのviewDidLoadでTableViewのヘッダーとフッターを設定
TableViewのヘッダーとフッターはセクションのようにdelegateメソッドを実装する必要はなく、
viewDidLoadで設定する。
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.dataSource = self
tableView.delegate = self
// TableViewのヘッダーを設定
let headerCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableHeaderCell")!
let headerView: UIView = headerCell.contentView
tableView.tableHeaderView = headerView
// TableViewのフッターを設定
let footerCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableFooterCell")!
let footerView: UIView = footerCell.contentView
tableView.tableFooterView = footerView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 行数
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "articleCell")!
return cell
}
// セクション数
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// セクションヘッダーの高さ
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
}