0

Can't access to function in parent view controller from a child via delegate/protocol. print() doesn't print.

In Child VC I have this:

protocol MyViewControllerDelegate: class {
    func requestExpandedView()
}
    
class MyViewController: UIViewController {
        
    weak var delegate: MyViewControllerDelegate?
    ...

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("\(indexPath) didSelectItemAt")
        
        delegate?.requestExpandedView()  
    }
}

In Parent VC I have this:

extension MessagesViewController: MyViewControllerDelegate {
    func requestExpandedView() {
        print("Done") // doesn't print anything
        requestPresentationStyle(.expanded)
    }
}

What's wrong?

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
Pavel
  • 3
  • 4
  • What are you trying to do here. The flow is a bit unclear. – PGDev Sep 23 '20 at 13:10
  • 3
    Did you set the `delegate` anywhere? – Roman Ryzhiy Sep 23 '20 at 13:11
  • Hi! I want to access to func (print("Done") for example) in my parent view controller from a child view controller via protocol-delegate (delegate?.requestExpandedView()) – Pavel Sep 23 '20 at 13:14
  • I guess that `print("\(indexPath) didSelectItemAt")` is printed, what's the value of `delegate`, is it `nil`? If yes, why is it nil? Did you set it somewhere? – Larme Sep 23 '20 at 13:14
  • Is `MyViewController` embedded in `MessagesViewController` ? – Dima G Sep 23 '20 at 13:15

1 Answers1

0

You need to set the delegate of MyViewController when creating its instance, i.e.

let vc = self.storyboard?.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController
vc.delegate = self
PGDev
  • 23,751
  • 6
  • 34
  • 88