Get Instance of ViewController from within extension

余生颓废 提交于 2019-12-11 14:12:29

问题


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:


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)


来源:https://stackoverflow.com/questions/51650475/get-instance-of-viewcontroller-from-within-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!