使って創ってApp

ソフトウェアを使ったり作ったりするブログです

UIテーブルビューを使ってみる

曲が一覧でズラッと並んだような表示を提供する、UITableViewを使ってみましょう。下の画像は、今回作成するアプリの完成予定図です。

f:id:hitxutokun:20151208213925p:plain

完成予定図

三名の 武将の名前が表示されています。

このアプリは結局何をやっているかというと、以下の配列の中身を表示しているだけです。

let busyous = [ "Takeda", "Uesugi", "Oda"]

この配列の中身を表示する手段として、TableViewを使用してます。

こんな単純なものでも、結構手間がかかるのです。

開発環境

UITableViewアプリを作成しよう!

適宜シミュレーターで実行して、動くか確認しながら作っていきましょう!

  1. まずは新規プロジェクトを作成しましょう。テンプレートは Single View Application を選択し、プロジェクト名は TableView Demo にしました。
  2. Main.storyboardを開き、メインのビューに TableView を追加します。それを目一杯広げて、上下左右がぴったりビューにくっつくように Constraints を追加します。

    f:id:hitxutokun:20151208220451p:plain

  3.  TableView を選択した状態で Attributes Inspector のPrototype Cells を1にします。TableView の表示が変わりましたか?追加されたものを「プロトタイプセル」と呼びます。"Takeda" "Uesugi"などが表示される基のセルです。

    f:id:hitxutokun:20151208221244p:plain

  4. 追加されたプロトタイプセルを選択して、Attributes Inspector の Identifier に Cell と入力します。

    f:id:hitxutokun:20151208222059p:plain

    f:id:hitxutokun:20151208222345p:plain

  5. TableView から 右クリックをしながら ViewController まで引っ張ります。右クリックを離したら表示される画面の dataSource と delegate を選択します。

    f:id:hitxutokun:20151208223522g:plain

  6. ViewController.swiftを開き、クラス宣言に UITableViewDelegate を追加します。 あと少しです!頑張りましょう!!

    // 変更前 class ViewController: UIViewController {
    class ViewController: UIViewController, UITableViewDelegate {
  7. viewDidLoad関数の上に、今回表示する内容を含んだ配列を書きます。

    let busyous = [ "Takeda", "Uesugi", "Oda" ]

    override func viewDidLoad() {
  8. 2つの関数を ViewController クラス内に追加します。

    • func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    • func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

    一つ目の関数は、TableViewのセクション中のセルの数を聞いています。今回は busyous 配列の要素数を返します。

    二つ目の関数は、TableView に表示するセルを作成します。busyous の要素を表示させましょう。

  9. 先ほどの関数の中身を書きます
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return busyous.count
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
      cell.textLabel?.text = busyous[indexPath.row]

      return cell
    }
    dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) は、手順4で "Cell" と名付けたプロトタイプセルを使い回すよ、というメソッドです。

完成!!

シミュレータで実行してみましょう。最初に見た画面が表示されましたか?

f:id:hitxutokun:20151208213925p:plain

表示されましたね。おめでとうございます!!これが TableView の基本的な使い方です。

まとめ

TableViewを使用するのに大事なのは以下4点です。

  • 表示する内容を持った配列を用意すること
  • dataSource, delegate を設定すること
  • func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
  • func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell