首先可以看 先前寫的這篇文章,瞭解如何在 TableViewCell 加入 Button
按照上篇文章
- 先建立 UITableViewCell 的子類別
- prototype cell 連結至剛建立的class
- 將元件 @IBOutlet 拉進class
- 完成如下圖
利用 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)
}
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 中。
Step4: 於cellForRow中,將delegate 指定給cell自己
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Mycell
cell.delegate = self
Step5: 實作protocol裡的function
sender 為Mycell 中的 func check(_ sender: UIButton) Button 點擊事件
完整程式碼如下~~~