はじめに
こんにちは
UITableViewHeaderFooterViewという
tableViewのセクションで利用できるViewです。
register(_: ,forHeaderFooterViewReuseIdentifier: )
という再利用のメソッドがtableViewにあるのですが、
画像のようにxibファイルを同時に作成できなくて困ったので、
まとめてみたいと思います。
至らぬ点など多々あると思いますが、コメントなど頂けたら幸いです。
カスタムClassとxibFileを作成する
UITableViewHeaderFooterViewを継承したカスタムClass
CustomHeaderFooterView.swift
import UIKit
class CustomHeaderFooterView: UITableViewHeaderFooterView {
@IBOutlet weak var view: UIView!
override func awakeFromNib() {
}
}
xibFile
通常のViewをxibで準備するように,
File -> New -> File... -> User InterfaceのViewを選択し、xibFileを作成します。
「Custom Class」を先ほど作成したCustomHeaderFooterViewに設定しています。
Simulated Metricsの設定やサイズを調節するとViewが見やすくなると思います。

ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
//xibの生成
let xib = UINib(nibName: "CustomHeaderFooterView", bundle: nil)
//再利用するための準備
tableView.register(xib, forHeaderFooterViewReuseIdentifier: "CustomHeaderFooterView")
}
TableViewのDelegateにSectionの再利用を求めます
extension ViewController: UITableViewDelegate{
//セクションの設定
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerFooterView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderFooterView") as! CustomHeaderFooterView
return headerFooterView
}
}
サンプルコード
一応、サンプルコード(動作させたViewController)を貼っておきたいと思います
ViewController.swift
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var tableView: UITableView!
var sectionData:[UIColor] = [UIColor.brown,UIColor.green,UIColor.cyan]
var cellData:[String] = ["セル 1","セル 2","セル 3"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
//セクションの高さを設定
tableView.sectionHeaderHeight = 44
//xibの生成
let xib = UINib(nibName: "CustomHeaderFooterView", bundle: nil)
//再利用するための準備
tableView.register(xib, forHeaderFooterViewReuseIdentifier: "CustomHeaderFooterView")
}
}
extension ViewController: UITableViewDataSource{
//テーブルの行ごとのセルを返却する
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = cellData[indexPath.row]
return cell
}
//テーブルの行数を返却
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellData.count
}
//セクションの個数を返します
func numberOfSections(in tableView: UITableView) -> Int {
return sectionData.count
}
}
extension ViewController: UITableViewDelegate{
//セクションの設定
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerFooterView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderFooterView") as! CustomHeaderFooterView
headerFooterView.view.backgroundColor = sectionData[section]
return headerFooterView
}
}
参考にさせていただいた記事
ありがとうございます。