見出し画像

Swiftでいこう。 -Swiftplaygrounds4

今回はTableViewを表示してみましょう。

基本形は

import UIKit
import PlaygroundSupport

class TableViewController : UITableViewController {
    
    
}

let tableViewController = TableViewController(style: .plain)

PlaygroundPage.current.liveView = tableViewController

UITableViewController classを使います。

まずは表示する内容を配列に入れて行きます。

var arr = ["a","b","c","d"]

そしてメソッドの上書き、修正をしていきます。

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
} // 1

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section)"
} //2

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = "Cell \(indexPath.section).\(indexPath.row).\(arr[indexPath.row])"
return cell
} //3

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section)"
} //4

としました。

1 では表示するテーブルの段の数を指定してやります。配列の数を取得(arr.count)してその数に合わせてます。  

2ではてテーブルの中でひとまとめできるセクションのタイトル、セクションの数を取得(\(section))を決めています。

3ではテーブルの段(cell)に何を表示するかを決めています。

indexPath.section セクションの番号、indexPath.row テーブルの段の番号、arr[indexPath.row] 配列 arr の中身の表示をさせます。

4ではセクションのタイトルを表示させます。この場合は文字“セクション”とセクションの番号を表示します。

それでは表示させたものです。

となります。

テーブルの一つの段、セルを押した時の動作を決めるときは、以下を追加してやればセルを押した時に、この場合はコンソールに”select”と表示されます。他のテーブルに移る、遷移する場合に使えます。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("select")
    }

この記事が気に入ったらサポートをしてみませんか?