从扩展中获取ViewController的实例

时间:2018-08-02 09:47:46

标签: ios swift extension-methods viewcontroller

我想从扩展中获得对 ViewController 访问权限,然后从库中覆盖一个函数,该函数应该更改变量或从特定的ViewController调用方法(在本例中为“ ViewController”)。

我该怎么做?还是有一个更推荐的选择?

(提示:我不想实例化新的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 个答案:

答案 0 :(得分:1)

您可以使用通知协议在ViewController之间进行通信

通知示例:

创建扩展以使用通知名称:

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

在First ViewController的DidLoad中添加Observer方法

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.
        }
    }

发布通知

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

协议

在ViewController B中创建协议和一个弱变量

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

weak var delegate: ProtocolB?

从A展示/推送ViewController B时

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

将协议方法添加到ViewController A

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

要触发方法调用:

delegate?.didUpdateScore(25)