はじめに
TableViewとCellの設定がたくさんあるので、知っている事を書いていきます。
※随時更新予定
TableViewの設定編
Cellの数
Cellの数が固定の場合(要素数が変化しない場合)
TableView → Content → [ Static Cells ]
Cellの数が可変の時(要素数が変化する場合)
TableView → Content → [ Dynamic Prototypes ]
設定場所 |
---|
セルの選択
選択不可
TableView → Selection → [ No Selection ]
選択可
TableView → Selection → [ Single Selection ]
複数選択
TableView → Selection → [ Single Selection ]
設定場所 |
---|
セクションヘッダーのスタイル変更
TableView → Style → [ Plain ] の場合 | TableView → Style → [ Grouped ] の場合 |
---|---|
一行分の高さで表示 | 二行分で表示 |
スクロールするとヘッダーが残る | スクロールしてもヘッダーは残らない |
設定場所 |
---|
Cellの設定
Cellの高さを可変にする
※TableViewの設定は省略します
1.Cell の ContentView に Label を追加する
2.Label に上下左右の制約をつける(Label→Linesは0に設定しておく)
3.Cellのカスタムクラスを作成する
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel! //4.の設定後に接続する
}
4.CellのCustomClassを設定し、LabelをOutlet接続する
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
まとめ
もう少し追加して、まとまりのある記事にしていこうと思います。