Nirakar Sapkota
Nirakar Sapkota

Reputation: 11

Protocol not passing to ViewController (Swift)

So I defined the ClickableCell protocol which is supposed to respond to tap gestures on an image. I want to redirect to ViewController2 when the user taps on the image, so my approach is to define a protocol, pass the info of tap to the CurrentViewController, and use the protocol in CurrentViewController to redirect to ViewController2. But I used print statements and it only printed "TAP TAP TAP" and "DONE" but not the portion from CurrentViewController. Can anyone help me figure out the problem? Thanks!

MessageCell.swift

protocol ClickableCell {

    func onTapImage(indexPath: IndexPath)

}

class MessageCell: UITableViewCell {



    @IBOutlet weak var leftImage: UIImageView!
    var cellDelegate: ClickableCell?
      var index: IndexPath?

    override func awakeFromNib() {
        super.awakeFromNib()
        self.setupLabelTap()
    }

    @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){
        print("TAP TAP TAP")
        cellDelegate?.onTapImage(indexPath: index!)
        print("DONE")
    }


    func setupLabelTap() {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(tapGestureRecognizer:)))
        self.leftImage.isUserInteractionEnabled = true
        self.leftImage.addGestureRecognizer(tapGestureRecognizer)

    }

}

CurrentViewController

extension CurrentViewController: ClickableCell {

    func onTapImage(indexPath: IndexPath) {
        print("Doesn't Print This")

         let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "nextView") as! UIViewController
        self.navigationController?.pushViewController(popOverVC, animated: true)
    }


}




Upvotes: 0

Views: 108

Answers (2)

Deviyani Swami
Deviyani Swami

Reputation: 767

You need to set the delegate. The core purpose of the delegate pattern is to allow an object to communicate back to its owner in a decoupled way.

So in cellForRowAt method:-

cell.delegate = self

Upvotes: 0

Asperi
Asperi

Reputation: 257729

You need to assign that cellDelegate when you create cell

extension CurrentViewController: UITableViewDataSource {
  // other your code here

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "your_message_cell_id", 
          for: indexPath) as! MessageCell

     /// other setup code here

     cell.cellDelegate = self // << here !!
     return cell
  }
}

Upvotes: 1

Related Questions