How to trigger protocol function in a view controller?


I create a protocol on my custom DeviceTableViewCell

protocol DeviceTableViewCellDelegate : NSObjectProtocol {
    func printMe(_ text : String)

I also declared my delegate in

weak var delegate: DeviceTableViewCellDelegate?


I had this

extension DevicesViewController: DeviceTableViewCellDelegate {

    func printMe(_ text : String) {
        let text = "Protocol & Delegate"


I don't know how to trigger my print() statement. How would one trigger it ?

Do I need to call my printMe() somewhere ?

Did I missing something here ?

3 answers

  • answered 2018-10-11 20:07 Naser Mohamed

    First, do this:

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

    Then, you must call printMe from your cell to handle your action

  • answered 2018-10-11 20:35 Đinh Quân

    You just declare how the delegate function working, you haven't called it yet. Based on the context, you can decide when to call delegate.printMe(_ text : "Foo").

    I suggest a simple example you could refer: passing data back to previous view controller from current view controller using delegate.

  • answered 2018-10-12 05:46 Jay Patel

    Let's take example to understand the concept. So as you already create delegate variable for your protocol.

    weak var delegate: DeviceTableViewCellDelegate?

    Now to call protocol method you need to assign your delegate to some viewController or class. Let's assign in same view controller in viewDidLoad method.

    override func viewDidLoad(){
       delegate = self

    Now let's say need to call protocol method when some button pressed. So what you need to do is call this method like this in button press method.

    delegate?.printMe("Button Pressed")