0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UITableViewの基礎

Last updated at Posted at 2021-04-23

■UITableViewとは

TODOリストなのでつかわれているもの
メモ帳のように
1行づつ文字を記入できる。

難しくなると色々できる。

■UIViewcontrollerにtableviewを置くCellを置く

スクリーンショット 2021-04-23 14.53.13.png

■cellを追加する
TableViewを選択して
こちらのPrototype cellsの数字を変えるとその分追加される。
スクリーンショット 2021-04-23 14.53.31.png

■TableViewのDelegateとDatasourceをUIViewControllerで使えるように

TableViewをcontrolをおしながら選択viewcontrollerに持っていく一番左の青色で囲まれてる奴
スクリーンショット 2021-04-23 14.59.08.png

■dataSourceとdelegateがでてるので順番にどっちも選択する。
スクリーンショット 2021-04-23 15.01.54.png

■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)
        }
    }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?