10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UITableViewでカスタムHeaderを使う方法

Last updated at Posted at 2019-06-12

サンプルコード

SectionHeaderView.swift
import UIKit

final class SectionHeaderView: UITableViewHeaderFooterView {

    static let height: CGFloat = 44

    @IBOutlet weak var titleLabel: UILabel!

    func setup(titleText: String) {
        titleLabel.text = titleText
    }
}
SampleViewController.swift

final class SampleViewController: UIViewController {

    @IBOutlet private weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
    }

    private func setupTableView() {
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self

        tableView.register(headerFooterViewClass: SectionHeaderView.self)
    }
}

extension SampleViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withClass: SectionHeaderView.self)
        header.setup(titleText: "Section title")
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SectionHeaderView.height
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
...

注意点

UITableViewのStyleを「Grouped」にすること。

デフォルトの「Plain」だとスクロールしてもHeaderが残ってしまうので、「Grouped」を指定します。

スクリーンショット 2019-06-12 11.59.02.png

heightForHeaderInSection, heightForFooterInSection を指定すること

参考: iOS11で Grouped UITableView のセクションヘッダーに余分な高さが出る問題について

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?