Swift UITableViewのセクションヘッダーをカスタマイズする方法メモ
やることは以下
・カスタムUIViewの実装
・viewForHeaderInSectionとheightForHeaderInSectionメソッドの定義
viewForHeaderInSectionはカスタムViewを返す
heightForHeaderInSectionはカスタムViewの高さを返す
テーブルセルのカスタマイズと考え方は同じ
カスタムUIViewの実装
class CustomeView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func setup(text: String) -> CGFloat {
let width = UIScreen.main.bounds.size.width
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width: height: 100))
label.text = text
addSubview(label)
return label.frame.height
}
}
viewForHeaderInSectionとheightForHeaderInSectionメソッドの定義
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
・・・
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = CustomeHeaderView()
let _ = header.setup(text: "...")
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let header = CustomeHeaderView()
return header.setup(text: "...")
}
・・・
}以上です