stevengbu stevengbu - 8 days ago 6
iOS Question

How do I insert code in ViewDidAppear and ViewDidDisappear From other class

I want to change button image whenever UISideMenuNavigationController Appear Or Disappear.

This is the class that has a button.

class MenuViewController: UIViewController {

@IBOutlet var btnMenu: UIButton!

override func viewDidLoad() {
super.viewDidLoad()
}
}


This is the other class that i want to insert code.

open class UISideMenuNavigationController: UINavigationController {

override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

// insert some code here but from MenuViewController class
}

override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)

// insert some code here but from MenuViewController class
}
}


I don't want to change UISideMenuNavigationController class because it is framework from pods.

I'm using framework side menu from https://github.com/jonkykong/SideMenu

I need to change button image whenever Side Menu Appear Or Disappear. I can't find the way from ReadMe Side Menu. That's why I think need to insert the code in ViewDidAppear and ViewDidDisappear Method from Side Menu Class but don't want to break the class.

Answer

You simply need to subclass UISideMenuNavigationController and override the viewDidAppear & viewDidDisappear methods to invoke a delegate.

protocol MyUISideMenuDelegate {
    func menuDidAppear(_ menu:MyUISideMenuNavigationController) -> Void
    func menuDidDisappear(_ menu:MyUISideMenuNavigationController) -> Void
}

open class MyUISideMenuNavigationController: UISideMenuNavigationController {

    var menuDelegate: MyUISideMenuDelegate? 

    override open func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
         self.menuDelegate?.menuDidAppear(self)
    }

    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.menuDelegate?.menuDidDisappear(self)
    }
}

Then have you view controller with the button implement the protocol and set itself as the delegate.

You could also have your menu subclass send NSNotification and have any other objects that are interested subscribe to those. This way you completely decouple the menu and the other classes.