LoginSignup
1
1

TableViewCellタップでアコーディオンでCollectionViewを表示する。

Last updated at Posted at 2023-06-28

tableViewのcellをタップした際にcellの下にアコーディオンでcollectionViewを表示させる方法をご紹介します。

■考え方

TableViewCellの下にCollectionViewを配置し、デフォルトではセルの高さだけを返す。
セルが開いた時にだけCell+CollectionViewの高さを返す。
スクリーンショット 2023-06-27 1.14.30.png

■実装方法

    //セル開閉のフラグを設定
    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
        }
    }
1
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
1
1