Table ViewのCellの個数を設定、中身を表示
2020/09/26確認
command + 1 して、Main.storyboardを選択して、画面を選択して、右上の+をクリックして、画面にTable Viewを追加します。
画面のTable Viewを選択して、一番右のボタンを選択して、OutletsのdataSouceの+をドラッグして、ViewController(タイトルバーの上の一番左のボタン)にドラッグします。
Outletsのdelegateの+をドラッグして、ViewController(タイトルバーの上の一番左のボタン)にドラッグします。
右上の+をクリックして、Table View Cellを画面のTable Viewにドラッグして追加します。
追加したTable View Cellに名前をつけます。右から3番目のボタンを選択して、Identifierをcellにします。
SwiftでTableViewを使ってみよう - Qiita
class ViewController: UIViewController
の後ろに
, UITableViewDelegate, UITableViewDataSource
を追加します。
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
エラーのアイコンをクリックして、Fixボタンを押すとコードが追加されます。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
<#code#>
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
<#code#>
}
let TODO = ["牛乳を買う", "掃除をする", "アプリ開発の勉強をする"]
を
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
の下に追加します。
Cellの個数を設定する処理を追加します。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TODO.count
}
Cellの中身を表示する処理を追加します。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// セルを取得する
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// セルに表示する値を設定する
cell.textLabel!.text = TODO[indexPath.row]
return cell
}
実行すると画面が表示されます。
006 UITableViewでテーブルを表示 · GitBook
【Swift】他クラスのデリゲートを自分のメソッドで使用する方法 - Qiita