Home > database >  Using button in custom cell from another ViewController
Using button in custom cell from another ViewController

Time:03-18

I created button in my custom cell which is I created to another class after that I added that cell on my tableView(in my viewController), when the user click the that button which is in custom cell, I have to segue another class and also I have to pass some data but problem is I could not segue in custom cell, so how can I detect when user tap that button ? or how can I take current index of that button which user tapped ?

CodePudding user response:

First you have to make one protocol on your custom table cell.

Then create one weak var in your table cell class.

After that make your button action in your custom table cell class and pass button tag from your table cell to view controller. From the button tag you can easily get which index button is clicked.

protocol CustomTableCellDelegate: AnyObject {
   func btnClicked(tag: Int)
}
class CustomTableCell: UITableViewCell {
 ..
 ..
 weak var customTableCellDelegate: CustomTableCellDelegate?

 ..
 ..

@IBAction func btnClicked(_ sender: UIButton) {
 self.customTableCellDelegate?.btnClicked(tag: sender.tag)
}  

Now in your viewcontroller (where your table cell is implementing and showing list in tableview) make one extension and give delegate to that extension.

extension YourViewController: CustomTableCellDelegate {
  func btnClicked(tag: Int) {
   // Here you can find the which button is clicked from the button tag. You can do segue or navigation from here.
  }
}

Make sure to do this. This is important

In your cellForRowAt method, write two below lines.

cell.customTableCellDelegate = self
cell.yourbutton.tag = indexPath.row
  • Related