TableViewCell偵測Button點擊的方法

Anny
Oct 16, 2020

--

如果想要在 TableView 的 Cell 中加入 Button , 那要如何偵測是哪一列的Button被點擊到的呢?我們必須知道是哪一列的 Button 被點擊,才能對那一列的 cell 做操作~~~

這邊介紹兩種偵測Button點擊的方法

  • 利用 tag
  • 利用 protocol

先讓我們看個範例

如果你也需要用到此功能的話,就讓我們繼續看下去吧!

首先可以看 先前寫的這篇文章,瞭解如何在 TableViewCell 加入 Button

按照上篇文章

  1. 先建立 UITableViewCell 的子類別
  2. prototype cell 連結至剛建立的class
  3. 將元件 @IBOutlet 拉進class
  4. 完成如下圖

利用 tag

Step1:
在 cellForRowAt indexPath 中,將 indexPath.row(也就是偵測cell是哪一列)
放進 Button 的 tag 裡,這樣就用 tag 來偵測點擊到cell 的哪一列Button。

button.tag = indexPath.row

Step2:

接著在 Button 點擊事件的 function 中 ,使用 sender.tag 將 button.tag 的直取出來。就可以來取得cell那列的資料囉~~~

注意!!!這裡的 Button 點擊事件的 function,為連結至 class TableViewController 中的。

完整程式碼如下~~~

利用 protocol

Step1: 建立 protocol,並且在內建立一個 function 帶進sender參數,取得MyCell : UITableViewCell 的 Button 屬性。

protocol MyCellDelegate{
func cellButtonAction(sender: Mycell)
}
Step1 完成樣子

Step2: 在所建立 UITableViewCell 的子類別中,宣告型態為 剛建立protocol 的 delegate變數。

var delegate: MyCellDelegate?

Step3: 並且在 Button 點擊事件的 function中,加入執行protocol的方法。
呼叫 執行protocol 帶有sender參數 的 function。

sender 為 self 意思則是 將自己的 Button 點擊事件 帶入!!!

@IBAction func check(_ sender: UIButton) {
delegate?.cellButtonAction(sender: self)
}

注意!!!這裡的 Button 點擊事件的 function,為連結至 class Mycell: UITableViewCell 中。

Step2&3 完成樣子

Step4: 於cellForRow中,將delegate 指定給cell自己

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Mycell
cell.delegate = self
Step4 完成樣子

Step5: 實作protocol裡的function

sender 為Mycell 中的 func check(_ sender: UIButton) Button 點擊事件

Step5 完成樣子

完整程式碼如下~~~

--

--

Anny
Anny

Written by Anny

If You Think You Can, You Can!

No responses yet