環境
- MacBook Air M1
- OS : 11.2(20D64)
- XCode : 12.4
- Swift : 5.3.2
参考
1. 新規ファイル追加でCocoa Touch Classを選択

2. 作成時の設定
- Class : 好きな名前(今回は
CustomTableViewCell
)
- Subclass of : UITableViewCell
- Also create XIB file : ON
- Language : Swift

2つの新規ファイルが生成されればOK

3. CustomTableViewCell.xibを編集
Cellにラベルを追加

Rostoration IDの設定
任意の文字列でいい(セル生成時に使用する)

4. CustomTableViewCell.swiftでラベルの参照を設定

5. Main.storyboardを編集
Table Viewを追加

6. ViewController.swiftを編集
Main.storyboardで指定した、Table Viewの参照を設定

viewDidLoad()に追記
- UITableViewに対して、delegateと使用する
Cell
の情報を設定
- TableView.register : 使用するカスタムセルの情報を登録
- nibName = 作ったCellのクラス名
- forCellReuseIdentifier = xibで指定したidentifier名
- TableView.delegate :
- TableView.dataSorce :
1 2 3 4 5 6 7 8 9 10
| override func viewDidLoad() { super.viewDidLoad()
TableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomCell") TableView.delegate = self TableView.dataSource = self }
|
UITableViewDelegate,UITableViewDataSourceを継承
- どちらのメソッドも、
optional
なので、最低限のメソッドの定義をすれば、他のメソッドは定義しなくてもいい
- UITableViewDelegate : TableView内のデータが選択や生成、編集されたときに呼び出されるメソッドが定義されたプロトコル群
- UITableViewDataSource : テーブルに表示させたいデータを設定するためのプロトコル群
1 2 3
| class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { ... }
|
継承すると、エラーが出るはずなので、Fixをクリックしてメソッドを2つ自動生成してもらうと、以下のようなメソッドが自動生成されるはず
1 2 3 4 5 6 7 8 9 10 11
| // UITableViewDelegateの継承によって生成された // TableViewに生成するセル数を設定する(Int型を返す) func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { Code }
// UITableViewDataSourceの継承によって生成された // TableViewに表示するセルのデータを設定する(UITableViewCellを返す) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { Code }
|
今回は、生成するセルを10個
、表示するデータを各セルを上から数えたときの番号
にする
1 2 3 4 5 6 7 8 9 10 11
| func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell",for: indexPath) as! CustomTableViewCell cell.Label.text = String(indexPath.row) return cell }
|
実行した結果

ViewController.swiftの完成形
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var TableView: UITableView! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell",for: indexPath) as! CustomTableViewCell cell.Label.text = String(1) return cell }
override func viewDidLoad() { super.viewDidLoad() TableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomCell") TableView.delegate = self TableView.dataSource = self }
}
|