1

DeviceTableViewCell

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?

DevicesViewController

I had this

extension DevicesViewController: DeviceTableViewCellDelegate {
    
   
    func printMe(_ text : String) {
        let text = "Protocol & Delegate"
        
        print("........")
        print(text)
        print("........")
    }
}

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 ?

Community
  • 1
  • 1
code-8
  • 54,650
  • 106
  • 352
  • 604
  • Which ever class has the `delegate` property (presumable your cell class) must call the `printMe` method at some appropriate time. Only you know how it is to be used and when it should be called. – rmaddy Oct 11 '18 at 20:02
  • You treat a delegate as a placeholder. In future, you can assign any role to this delegate. – E.Coms Oct 11 '18 at 20:11

3 Answers3

0

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

0

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.

Đinh Quân
  • 71
  • 2
  • 8
0

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")
Jay Patel
  • 343
  • 2
  • 19