Vo Kim Nguyen Vo Kim Nguyen - 4 months ago 8
Objective-C Question

Re-use function on every UIVIewController

I have a function that use very common on every UIViewController

func backPreviousScreen() {
self.navigationController?.popViewControllerAnimated(true)
}


Is anyway that I don't have to write detail that function above on each UIViewController ?, just need some method like I can inherit it, and use it in all UIViewController ?

Answer

You can create a protocol and add extension to it:

protocol Dismissable  {
}

extension Dismissable  where Self: UIViewController  {
    func backPreviousScreen() {
        self.navigationController?.popViewControllerAnimated(true)
    }
}

Now just mark the view controller class with this protocol and you are ready to go:

class MyViewController: UIViewController, Dismissable  {

}
Comments