tableViewのcellをタップした際にcellの下にアコーディオンでcollectionViewを表示させる方法をご紹介します。
■考え方
TableViewCellの下にCollectionViewを配置し、デフォルトではセルの高さだけを返す。
セルが開いた時にだけCell+CollectionViewの高さを返す。
■実装方法
//セル開閉のフラグを設定
var isCellOpen = false
var selectedIndexPath: Int?
// セルタップ時の処理
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "collectionView", for: indexPath) as! CollectionView
if selectedIndexPath == indexPath.row {
//選択中のセルがタップしたセルと同様だったらfalseが返される
isCellOpen = false
} else {
isCellOpen = true
}
selectedIndexPath = indexPath.row
tableView.reloadData()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if selectedIndexPath == indexPath.row {
if isCellOpen == false {
//セルを閉じた時の高さを指定(Cellの高さ)
return 40
}
//セルを開いた時の高さを指定(Cell+CollectionViewの高さ)
return 200
} else {
//初期状態の高さを指定(Cellの高さ)
return 40
}
}