LoginSignup
23

More than 5 years have passed since last update.

[iOS][Swift]UITableViewのヘッダーとフッターを設定する方法

Posted at

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

1. Storyboardでヘッダーとフッター用のUITableViewCellを用意

スクリーンショット 2017-03-20 20.23.49.png

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
    }
}

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
23