get indexPath of UITableViewCell on click of Button from Cell

Use Delegates:

MyCell.swift:

import UIKit

//1. delegate method
protocol MyCellDelegate: AnyObject {
    func btnCloseTapped(cell: MyCell)
}

class MyCell: UICollectionViewCell {
    @IBOutlet var btnClose: UIButton!

    //2. create delegate variable
    weak var delegate: MyCellDelegate?

    //3. assign this action to close button
    @IBAction func btnCloseTapped(sender: AnyObject) {
        //4. call delegate method
        //check delegate is not nil with `?`
        delegate?.btnCloseTapped(cell: self)
    }
}

MyViewController.swift:

//5. Conform to delegate method
class MyViewController: UIViewController, MyCellDelegate, UITableViewDataSource,UITableViewDelegate {

    //6. Implement Delegate Method
    func btnCloseTapped(cell: MyCell) {
        //Get the indexpath of cell where button was tapped
        let indexPath = self.collectionView.indexPathForCell(cell)
        print(indexPath!.row)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell
        //7. delegate view controller instance to the cell
        cell.delegate = self

        return cell
    }
}

Leave a Comment