0

I'd like to get access to a ViewController from an extension and then override a function from a library which should change variables or invoke methods from a specific ViewController (in this case "ViewController").

How can I do that? Or is there a more recommended option?

(Hint: I don't want to instantiate a new VC)

import PopupDialog

class ViewController: UIViewController {

    //e.g. variable and method to access from extension

    var score: Int = 0;

    func startGame(){
        ...
    }
}
extension PopupDialog{
    open override func viewWillDisappear(_ animated: Bool) {
        //change variables
        //maybe also invoke methods
    }
}

1 Answers1

1

You can use Notification or Protocol to communicate between ViewControllers

Notification Example:

Create an Extension to use Notification names:

extension Notification.Name {
    static let ScoreUpdateNotification = Notification.Name("ScoreUpdateNotification")
}

Add Observer method in First ViewController's DidLoad

NotificationCenter.default.addObserver(self, selector: #selector(triggerThisMethod), name: Notification.Name.ScoreUpdateNotification, object: nil)

@objc func triggerThisMethod(_ notification: NSNotification) {
        // When the notification arrives, this method will be called
        if let object = notification.object {
            // If there is Object passed with notification you will get it here.
        }
    }

To Post Notification

let objectToPass = 23
NotificationCenter.default.post(name: .ScoreUpdateNotification, object: objectToPass)

Protocol

Create Protocol and a weak variable in ViewController B

protocol ProtocolB: class {
    func didUpdateScore(_ score: Int)
}

weak var delegate: ProtocolB?

When you Present/Push ViewController B from A

let viewControllerB = // ...
viewControllerB.delegate = self
//present viewControllerB

Add Protocol Methods to ViewController A

extension ViewController: ProtocolA {
    func didUpdateScore(_ score: Int) {
        // Do things
    }
}

To trigger methods call:

delegate?.didUpdateScore(25)
Community
  • 1
  • 1
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
  • Thank you very much! I'll try both ways, I think I could get in trouble because I only have one ViewController class file and from there I just invoke a new one modally. So I have no file for ViewController B (I'll accept your answer later, when everything is fine) – Cedric Michael Aug 02 '18 at 10:58
  • `PopupDialog` ? What's this about? Is it a viewcontroller? NB: You don't have to use both way. Use the convenient one. Normally notifications are used when you Trigger multiple observers. – Lal Krishna Aug 02 '18 at 11:32
  • Yes it is! Worked fine with the notification pattern, but I'm posting the notification in my viewWillDisappear() from the PopUpDialog extension. – Cedric Michael Aug 02 '18 at 16:22