UITableViewCell
完成図はこんな感じ
プロジェクト新規作成 → 「SingleView Application」を選択 → product Nameは「SampleCell」で作成。
初期から存在するView Controllerに「TableView」をドラッグ&ドロップする。
ドロップしたTableVIewをViewControllerの全体に広げる。
TableViewの上にTableViewCellをドラッグ&ドロップする。
「Table View Cell」を選択し、Attributei nspecterの中のidentifierの項目に「Cell」を入力する。
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で保存&ビルドを実行。