bigmac-jp blog

web開発関連のメモ

UITableViewCell

完成図はこんな感じ

f:id:mtaryo:20170101154858p:plain





プロジェクト新規作成 → 「SingleView Application」を選択 → product Nameは「SampleCell」で作成。

f:id:mtaryo:20170101155555p:plain



初期から存在するView Controllerに「TableView」をドラッグ&ドロップする。
f:id:mtaryo:20170101160018p:plain
ドロップしたTableVIewをViewControllerの全体に広げる。
f:id:mtaryo:20170101220107p:plain
TableViewの上にTableViewCellをドラッグ&ドロップする。
f:id:mtaryo:20170101220415p:plain

「Table View Cell」を選択し、Attributei nspecterの中のidentifierの項目に「Cell」を入力する。
f:id:mtaryo:20170105220247p:plain

ViewController.swiftを選択する。
下記のようにソースを修正する。

import UIKit

// ①修正(UITableViewDataSource, UITableViewDelegate)
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //②追加
    //テーブルの行数を返却する
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    //③追加
    //テーブルの行ごとのセルを返却する
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = String(indexPath.row)
        return cell
    }
}

②と③のメソッドはUITableViewDataSourceの必須メソッドなので、記述なしだとエラーになる。

UITableViewDelegateとUITableViewDataSourceプロトコルの処理を行うクラスを、UIViewControllerの継承先のViewContollerに関連づける。
「ViewControllerScene」ツリーの「View Controller」→「View」→「Table View」を選択した状態でControlキーを押しながら、「View Controller」にドラッグ&ドロップする。ポップアップ画面が表示されるので、「dataSource」を選択する。 ドラッグ&ドロップを再度行い、「delegate」を選択する。これで関連付けが完了する。

Xcodeで保存&ビルドを実行。
f:id:mtaryo:20170105233927p:plain