TableViewの使い方

目的

TableViewで出来ることを模索する

→ TODOアプリなんかはTableViewを極めれば、ライブラリを使わずに実装できそう
追加、削除、データー配置移動まで出来る

反省点:セクションも入れたのでちょっと処理が面倒になった

作成手順

1.stroyboardにTableViewを追加(画面一杯まで)
2.TableViewCellを追加(1つだけでOK)
3.cellのIdentifier(識別子)を設定
4.NavigationControllerを追加(画面遷移用)
5.TableViewをView Controllerと関連付けする
6.セルのデータを指定する
7.セルのデータ数を指定する
——ここまでで、最低限の実装。ビルドできる
8.テーブルをセクションに分ける
9.テーブルが選択された時に画面遷移させる
10.テーブルの挿入・削除
11.テーブルのデータ移動

cellのIdentifier(識別子)設定方法

やり方は2通り。
A)のやり方の方が、楽。ただ、Bの方がソースからは追いやすい。

A) storyboard上で設定する
f:id:nananiku-s-60:20190122223118p:plain

B) ソースコード上で設定する
識別子を”cellTest”に設定する
識別子がない場合は、if文の中に入ってデフォルト値を設定する

// テーブルの行ごとのセルを返却する
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellTest")
if cell == nil {
cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: cellIdentifier)
}
cell?.textLabel?.text = todoList[indexPath.row]
return cell!
}

NavigationControllerの追加方法

Editor > Embed In > NavigationControllerで追加
f:id:nananiku-s-60:20190122223142p:plain

TableViewをView Controllerと関連付けする

1) 「Control」キーを押しながら、「TableView」を「View Controller」にドラッグ&ドロップ
2) Outletsの「dataSource」と「delegate」の両方を関連付ける
f:id:nananiku-s-60:20190122223157p:plain

3) ViewControllerにUITableViewDataSource, UITableViewDelegateプロトコルを宣言する

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

セルのデータ数を指定する

todoListは配列。
配列の数をretrunしてるだけ

// テーブルの行数を返却する
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todoList.count
}

セルのデータ(表示内容)を指定する

indexPathが、テーブルの何番目かをさす

// テーブルの行ごとのセルを返却する
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: cellIdentifier)
}
cell?.textLabel?.text = todoList[indexPath.row]
return cell!
}

テーブルをセクションに分ける

1) セクション用の配列を用意。合わせて、セクション内に表示する配列も変更

var sectionList = ["section1","section2"]
var todoList = [["1","2"], ["1","2","3"]]

2) セクションの数を指定

// セクションの数を指定
func numberOfSections(in tableView: UITableView) -> Int {
return sectionList.count
}

3) セクションのタイトルを設定

// セクションのタイトルを設定
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionList[section]
}

4) テーブルの行数の返し方を変更
indexPathの中にセクションの情報もあるので設定する

// テーブルの行数を返却する
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todoList[section].count
}
// テーブルの行ごとのセルを返却する
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: cellIdentifier)
}
// セルのタイトルの設定
cell?.textLabel?.text = todoList[indexPath.section][indexPath.row]
return cell!
}

テーブルが選択された時に画面遷移させる

1) 遷移先の画面を作成する
    ・storyboardにViewController追加
    ・Idetitiyを設定
f:id:nananiku-s-60:20190122223419p:plain

 ・新しくViewControllerクラス作成
 ラベルと、遷移元から渡させる文字列を設定する変数”text”を用意

import Foundation
import UIKit
class TableViewCellController: UIViewController {
@IBOutlet weak var lable: UILabel!
var text: String?
override func viewDidLoad() {
super.viewDidLoad()
lable.text = self.text
}
}

3) セル選択時の処理を追加

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// ストリートボードから遷移先のクラス名を取得
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// 1)で設定したIdetitiyを指定して取得
let vc = storyboard.instantiateViewController(withIdentifier: "cellCon") as! TableViewCellController
// タイトルとラベルに設定する文字列を指定
vc.title = sectionList[indexPath.section]
vc.text = todoList[indexPath.section][indexPath.row]
// 遷移先のページを設定
self.navigationController?.pushViewController(vc, animated: true)
}

テーブルの挿入・削除

1) Editボタンの設定

override func viewDidLoad() {
super.viewDidLoad()
// Editボタンを右上に配置
self.navigationController?.isNavigationBarHidden = false
navigationItem.title = "TableView"
navigationItem.rightBarButtonItem = editButtonItem
}

2) テーブルのEditボタン押下時の設定

// テーブルの編集権限
override func setEditing(_ editing: Bool, animated: Bool) {
// override前の処理を継続してさせる
super.setEditing(editing, animated: animated)
// tableViewの編集モードを切り替える
if editing {
let newIndexPath = IndexPath(row: todoList[1].count, section: 1)
todoList[1].append("登録する")
self.tableView.insertRows(at: [newIndexPath], with: UITableView.RowAnimation.fade)
} else {
let indexPath = IndexPath(row: todoList[1].count-1, section: 1)
todoList[1].remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.fade)
}
tableView.isEditing = editing
}

3) テーブルのセルの編集権限設定

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// セクション0は編集させない
if indexPath.section == 0 {
return false
}
return true
}

4) テーブルの編集形式を設定

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if indexPath.section == 1 && todoList[1].count == indexPath.row + 1 {
return UITableViewCell.EditingStyle.insert
}
return UITableViewCell.EditingStyle.delete
}

5) テーブルのセルを挿入/削除する

// テーブルのセルを挿入/削除する
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCell.EditingStyle.delete) {
todoList[indexPath.section].remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.fade)
} else if (editingStyle == UITableViewCell.EditingStyle.insert) {
todoList[indexPath.section].insert(String(indexPath.row+1), at: todoList[1].count-1)
self.tableView.insertRows(at: [indexPath], with: UITableView.RowAnimation.fade)
}
}

テーブルのデータ移動

1) テーブルのデータ移動権限設定

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// セクション1の最初の1行目だけ移動を許可させない
if indexPath.section == 1 && 0 == indexPath.row {
return false
}
return true
}

2) テーブルのデータを移動する

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// 特に処理は必要なし
}

用語

UITableViewDelegate

テーブルが操作された時にどんなアクションを行うか

UITableViewDataSource

テーブルの表示にどんなデータを使うか定義

参考URL

tableViewについて色々調べていて一番わかりやすかったサイト

https://pg-happy.jp/swift-tableview-tableviewcell.html

tableの編集について参考にしたサイト

https://qiita.com/nasutaro211/items/50d1dbc89969d873b7da

サンプル

https://github.com/satoNobu/study_swift/commit/69633e5fbc75da2c0234e171482210c959ca6abf

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です