I have an action button in UITableViewCell and I would like to detect when the button is pressed and the pressed cell's number from ViewController to make an audio play list in ViewController.swift.
I have been stuck in this problem for a while and I would really appriciate your advice. Here are the codes.
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell
return cell
}
}
Cell.swift
import UIKit
class Cell: UITableViewCell {
@IBOutlet weak var button: UIButton!
@IBAction func buttonPressed(_ sender: Any) {
***[Code to send the pressed cell's number to ViewController]***
}
}
You could go for a good old fashioned delegate pattern. This has the advantage of not coupling your view controller from your cell. Don't forget to make your delegate weak
to avoid retain cycles.
The you can find the cell index path from the table view. (I'm assuming by cell number you mean index path)
protocol CellDelegate: class {
func didTap(_ cell: Cell)
}
class Cell: UITableViewCell {
weak var delegate: CellDelegate?
@IBAction func buttonPressed(_ sender: Any) {
delegate?.didTap(self)
}
}
class ViewController: UIViewController, CellDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ...
cell.delegate = self
return cell
}
func didTap(_ cell: Cell) {
let indexPath = self.tableView.indexPath(for: cell)
// do something with the index path
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With