Search code examples
iosuiviewcontrollerseguepushviewcontrollerpresentviewcontroller

Is there any way to make a controller only presentable in iOS (maybe in macOS too)?


EDIT: The accepted answer is fulfilling my needs but I'm still open to different approaches.

I came up with this question. I have a controller and I want it to be only presentable. If some controller tries to push it or tries to show it with other segues, the app shouldn't show it. Let me clarify with an example:

class OnlyPresentableController : UIViewController{

    ///imagine a variable like this exists.
    override var isOnlyPresentable : Bool{
        return true
    }
    //........
}


class SomeController : UIViewController{

    //.....

    @IBAction func aButtonClick(_ sender: UIButton) {

        let controller = OnlyPresentableController(nibName: "OnlyPresentableController", bundle: Bundle.main)

       //this will work
       present(controller, animated: true, completion: nil)
    }
    @IBAction func anOtherButtonClick(_ sender: UIButton) {

        let controller = OnlyPresentableController(nibName: "OnlyPresentableController", bundle: Bundle.main)

        //this will not work because controller is an only presentable one.
       navigationController?.pushViewController(controller, animated: true)
    }

}

So what do you think? Is this implementable?


Solution

  • So I have an idea about preventing pushing. You can use Swizzling to swizzle pushViewController function. So in the swizzles function you check if view controller is instance of OnlyPresentableController and then you do nothing, if not you can proceed with pushing.

    Note: I'm assuming you know about Method Swizzling