LoginSignup
5
8

More than 5 years have passed since last update.

StoryboardでTableViewを使う(UITableViewカスタムクラス不使用

Last updated at Posted at 2017-06-02

悩み

UITableViewを使っているとき、小手先のDelegate実装やらUITableViewControllerなどのおかげで、
いつも以下のようなことを考えもやもやしていた。

  • UITableViewDataSourceの実装をしたいのであって、UITableViewUITableViewControllerを触りたいわけじゃない。
  • そしてUITableViewDataSourceのコードしか実質書いてない。
  • 分割したい
  • これはおかしい。あるべきものはあるべきところへ収まらなければならない。
  • 分割したい分割したい分割したい
  • せっかくUITableViewDataSourceUIViewControllerから分離したのに、結局initdataSourceのためにインスタンスを生成するだけのUIViewControllerカスタムクラスを書いている。
  • こんな無駄なクラスは抹消しなくてはならない。
  • 削除したい削除したい削除したい

ということでStoryboardできちんとOutletを貼って、必要十分なクラスでTableViewを使いましょう。

手順

プロジェクトの作成

  • シングルビュープロジェクトを作成する

TableViewを配置する

  • Main.storyboardを開き、デフォルトで存在するViewControllerTableViewを配置する

スクリーンショット 2017-06-02 19.52.15.png

TableViewCellを配置する

  • TableViewTableViewCellを追加する。
  • cellのIdentifierにはcellをセットする

スクリーンショット 2017-06-02 19.53.04.png

UITableViewDataSourceを実装する

  • UITableViewDataSourceを実装したNSObjectのカスタムクラスを作成する

例として、8時、9時、10時をそれぞれ15分刻みにセルで出力する。


import UIKit

class DataSource: NSObject, UITableViewDataSource {
    let sections = [8, 9, 10]
    let rows = [0, 15, 30, 45]

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let hour = sections[section]
        return String(format: "%02d:00〜", hour)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rows.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        let hour = sections[indexPath.section]
        let minute = rows[indexPath.row]
        cell.textLabel?.text = String(format: "%02d:%02d", hour, minute)
        return cell
    }
}

StoryboardにDataSourceを追加する

ObjectViewControllerに追加する

スクリーンショット 2017-06-02 20.05.13.png

そして、ObjectのカスタムクラスにDataSourceを指定する。

スクリーンショット 2017-06-02 20.05.50.png

TableViewとDataSourceを繋ぐ

TableViewを右クリックしてメニューを開き、dataSourceのOutletをDataSourceオブジェクトを繋ぐ。

スクリーンショット 2017-06-02 20.06.17.png

実行する

ビルドして動作が確認できれば完成。

Simulator Screen Shot 2017.06.02 21.13.14.png

UITableViewのカスタムクラスなんていらなかったのだ。
UITableViewDelegeteも同じ要領で実装できる。

5
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
5
8