■UITableViewとは
TODOリストなのでつかわれているもの
メモ帳のように
1行づつ文字を記入できる。
難しくなると色々できる。
■UIViewcontrollerにtableviewを置くCellを置く
■cellを追加する
TableViewを選択して
こちらのPrototype cellsの数字を変えるとその分追加される。
■TableViewのDelegateとDatasourceをUIViewControllerで使えるように
TableViewをcontrolをおしながら選択viewcontrollerに持っていく一番左の青色で囲まれてる奴
■dataSourceとdelegateがでてるので順番にどっちも選択する。
■dataSourceのメソッドとdelegateメソッドを使う
■datasourceメソッド
見た目を整える
//セルの数を決める.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
//セルに値を設定する。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
■cellForRowAtメソッドの中身
まずcellのidentifireにIDを与える.
cellはこのcellやでと紐づける。
let cell = tableView.dequeueReusableCell(withIdentifier: "cellのidentifire名", for: indexPath)
■delegateメソッド
//セルを選択したら何かする。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
■よく使う引数indexPath.rowは行の数分になる。
numberOfRowsInSectionの返り値に
Array.count配列の数を与えたとしたら
indexPathはその行を指しrowは数を示す.
:注意:
indexPath.rowはインデックス番号を取得するので
配列の中身が10個の場合
indexPath.rowは10個文のインデックス番号を取得している。
0.1.2.3.4.5.6.7.8.9
の10個分のインデックス番号が入る。
■tableView.reloadData() 画面上で更新したい時に使う
例:TODOリストでやる事を追加するときにtableView.reloadData()を使用して更新で追加される。
textFieldを使用してやる事を追加するパターン
//このメソッドをButtonなり使いたい場所に記載する。
func textAdd() {
if textField.text != nil {
//textを配列に追加
self.textArray.append(textField.text ?? "")
//tableviewを更新
self.tableView.reloadData()
textField.text = ""
}
textField.endEditing(true)
}
■cellをスワイプして消去
cellの消去ボタンが押された時の処理
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
textArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}