UITableViewの使い方を解説していきます。

UITableViewを使う

「UITableView」を画面に表示するには普通の「ViewController」に「UITableView」を配置するか、「UITableViewController」を使う方法があると思いますが、今回は「UITableView」を配置するやり方を解説します。
「UITableViewController」を使う方法はこちら
UITableViewを配置する
まずは、「Main.storyboard」で「UITableView」を配置していきます。
「TableView」をドラッグして「ViewController」の上に配置します。

配置したら画面の角に置き、全体に広げます(部分的に使うことも可能です)。


次に、「TableViewCell」をドラッグして「TableView」の上に配置します。

配置したら「TableView」の中のcellを選択し、「Identifier」を入力します(今回は「reuseIdentifier」にします)。

「Assistant」を開きます。

「Assistant」を開いたら「TableView」を選択し、「controlキー」を押しながらコードのところまでドラッグします。

名前を「tableView」にし、「Connect」を選択します。


コードを書く
コードを書いていきます。
まず、下のようにclassのところに「UITableViewDelegate」と「UITableViewDataSource」を追加し、「viewDidload()」の中に「tableView.delegate = self」と「tableView.datasource = self」を追加します。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
}
エラーが出たと思うのでメソッドを追加していきます。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
//dequeueReusableCellのwithIdentifierはセルのidentifierと同じものにします
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
return cell
}
今回は配列を表示するようにしたいので配列を追加し、セルに表示するようにします。
全体のコードです
//
// ViewController.swift
// UITableView
//
// Created by user on 2021/06/20.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
//配列を追加
var languages: [String] = ["Swift", "Java", "Ruby", "Javascript", "PHP"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
//TableViewに表示するセルの数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return languages.count
}
//dequeueReusableCellのwithIdentifierはセルのidentifierと同じものにします
//cellのテキストに配列を表示するようにします
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = languages[indexPath.row]
return cell
}
}
これでtableに表示されるようになりました。