-2

Scenario: I have a table view and a custom button cell. In controller of cell I have made a delegate to call a function of MainController. Issue is my cell button action is firing but the delete function not.

CustomCell Controller:

import UIKit

protocol CustChatButtonDelegate: class {
    func chatActionClick(cell: CustButtonCell)
}
class CustButtonCell: UITableViewCell {

    var delegete:CustChatButtonDelegate?
     @IBOutlet weak var btnChat: UIButton!

    override func prepareForReuse() {
        super.prepareForReuse()
//        self.delegete=nil
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    @IBAction func btnChatActionClick(_ sender: Any) {
        print("btn click")
        self.delegete?.chatActionClick(cell: self)
    }

}

MainController:

import UIKit

class ChatController: UIViewController ,UITableViewDelegate, UITableViewDataSource, ChatButtonDelegate,CustChatButtonDelegate {

func chatActionClick(cell: CustButtonCell) {
        print("btnClicked")
    }

}
Hamish
  • 78,605
  • 19
  • 187
  • 280
Share Knowledge
  • 121
  • 1
  • 7
  • 1
    add `cell.delegate = self` where you creating the cell – Karthikeyan Bose Aug 16 '17 at 08:03
  • Have you set the delegate property of the CustButtonCell? Also, you might want to declare the delegate as `weak` because you would otherwise have a reference cycle. – Palle Aug 16 '17 at 08:03
  • where is your `.delegate = self` (or something similar) in your code? or in other words, where did you assign a value to the `delegate` var? – holex Aug 16 '17 at 08:04
  • cell.delegate = self worked for me thanks alot ^_^ .Please add your comment as separate answer. – Share Knowledge Aug 16 '17 at 08:07

2 Answers2

8

This is a fairly common issue.

Simply add cell.delegate = self where you are creating the cell, for example in cellForRowAt.

Also make your delegate property weak.

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
0

Delegating object should maintain a weak reference to its delegate.

weak var delegete: CustChatButtonDelegate?

Please note that strong is applied on object references by default.

choofie
  • 2,575
  • 1
  • 25
  • 30