LoginSignup
5
3

More than 3 years have passed since last update.

TableViewとCellのいろいろな設定

Last updated at Posted at 2021-02-24

はじめに

TableViewとCellの設定がたくさんあるので、知っている事を書いていきます。
※随時更新予定

TableViewの設定編

Cellの数

Cellの数が固定の場合(要素数が変化しない場合)

TableView → Content → [ Static Cells ]

Cellの数が可変の時(要素数が変化する場合)

TableView → Content → [ Dynamic Prototypes ]

設定場所
スクリーンショット 2021-02-24 10.26.20.png

セルの選択

選択不可

TableView → Selection → [ No Selection ]

選択可

TableView → Selection → [ Single Selection ]

複数選択

TableView → Selection → [ Single Selection ]

設定場所
スクリーンショット 2021-03-03 17.30.20.png

セクションヘッダーのスタイル変更

TableView → Style → [ Plain ] の場合 TableView → Style → [ Grouped ] の場合
スクリーンショット 2021-02-24 14.08.47.png スクリーンショット 2021-02-24 14.10.20.png
一行分の高さで表示 二行分で表示
スクロールするとヘッダーが残る スクロールしてもヘッダーは残らない
設定場所

Cellの設定

Cellの高さを可変にする

※TableViewの設定は省略します
1.Cell の ContentView に Label を追加する

2.Label に上下左右の制約をつける(Label→Linesは0に設定しておく)
スクリーンショット 2021-02-24 17.51.22.png
3.Cellのカスタムクラスを作成する

class CustomTableViewCell:  UITableViewCell {
    @IBOutlet weak var label: UILabel! //4.の設定後に接続する
}

4.CellのCustomClassを設定し、LabelをOutlet接続する
スクリーンショット 2021-02-24 17.48.15.png

5.以下のコードを設定する

    // 任意
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
      return 90 // セルの仮の高さ見たいなもの
    }

    // 必須
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        UITableView.automaticDimension // 高さが自動的になる設定
    }

Cellをアニメーション付きでTableViewに追加する

以下の1、2のコードを、Cellを追加する際に記述する。

        tableView.beginUpdates() // 1
        tableView.insertRows〜〜〜〜 // Cellの追加処理
        tableView.endUpdates() // 2

ezgif.com-gif-maker (3).gif

まとめ

もう少し追加して、まとまりのある記事にしていこうと思います。

5
3
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
5
3