接續昨天的問題,我們要能確定哪個 collection view 的 item 被點選,這樣我們才能知道我們要切換到哪個table view,所以我們會用到 collectionView(didSelectItemAt indexPath: IndexPath) 的方法。
雖然這是 table view 裡面的其中一個 cell,但因為這個 cell 是鑲入 collection view 的 cell,所以這個 cell 的類別也含有 UICollectionViewDelegate, UICollectionViewDataSource。
因為我們要確定哪個 collection item 被選擇,就會需要用到 collectionView(didSelectItemAt indexPath: IndexPath) 的方法,就只能把方法寫在這個類別裡面。
protocol SelectedCollectionItemDelegate {
    func selectedCollectionItem(index: Int)
}
class CellWithCollection: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var delegate: SelectedCollectionItemDelegate?
    
// ... 程式碼略
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //print(indexPath.row)
        let itemNum = indexPath.row
        self.delegate?.selectedCollectionItem(index: itemNum)
    }
除了讓 ViewController 遵守協議之外,還要設定 tableviewcell 的代理
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SelectedCollectionItemDelegate {
//...部分程式碼略
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 1 {
            let table_cell_2 = tableView.dequeueReusableCell(withIdentifier: "CellWithDrink", for: indexPath) as! CellWithDrink
            table_cell_2.drinkNameLabel.text = drinkList[indexPath.row]
            return table_cell_2
        
        } else {
            let table_cell = tableView.dequeueReusableCell(withIdentifier: "CellWithCollection", for: indexPath) as! CellWithCollection
            // 設定含有collection view 的 cell的代理為self = ViewController
            table_cell.delegate = self
            return table_cell
        }
    }
}
    func selectedCollectionItem(index: Int) {
        print("Selected item \(index)")
    }
