iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 25
0
Software Development

無中生有-從SWIFT語法學習到iOS APP的開發系列 第 25

哪個儲存格被選取

前言

接續昨天的問題,我們要能確定哪個 collection view 的 item 被點選,這樣我們才能知道我們要切換到哪個table view,所以我們會用到 collectionView(didSelectItemAt indexPath: IndexPath) 的方法。

1. 設定 protocol 協議

說明:

雖然這是 table view 裡面的其中一個 cell,但因為這個 cell 是鑲入 collection view 的 cell,所以這個 cell 的類別也含有 UICollectionViewDelegate, UICollectionViewDataSource。
因為我們要確定哪個 collection item 被選擇,就會需要用到 collectionView(didSelectItemAt indexPath: IndexPath) 的方法,就只能把方法寫在這個類別裡面。

在 CellWithCollection.swift 加入協議

protocol SelectedCollectionItemDelegate {
    func selectedCollectionItem(index: Int)
}

接著在 class CellWithCollection 中呼叫 collectionView(didSelectItemAt indexPath: IndexPath)

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)

    }

2. 回到 ViewController.swift 中,遵守SelectedCollectionItemDelegate 實作 func selectedCollectionItem(index: Int)

讓 ViewController 遵從 SelectedCollectionItemDelegate

除了讓 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)

    func selectedCollectionItem(index: Int) {
        print("Selected item \(index)")
    }

完成


上一篇
Day24 - 鑲嵌 Collection View 進 Table View
下一篇
Day26 - 充實我的飲料訂購App
系列文
無中生有-從SWIFT語法學習到iOS APP的開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言