Navigation controller simply with Swift?

2019-09-21 16:31发布

问题:

I have 3 view controllers I load from story board :

controller1  = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
controller2 = storyboard.instantiateViewController(withIdentifier: "ModelController") as! ModelController
controller3  = storyboard.instantiateViewController(withIdentifier: "BuyController") as! BuyViewController

I would like to create, and load these 3 controllers into a bottom navigation bar with 3 buttons.

Programmatically .

How would I do that with just a simple few lines of code ?

回答1:

I made a sample Project for you to do that

Check at - https://drive.google.com/open?id=1M12Nv4PLNUePSJFHf7w8b08M2_mWcUEC

Some refereeing code

My Three VC Objects

private lazy var ThirdObject: VC3 =
    {
        // Instantiate View Controller
        let viewController = self.storyboard?.instantiateViewController(withIdentifier: "VC3") as! VC3

        // Add View Controller as Child View Controller
        self.addChildViewController(viewController)
        return viewController
    }()


    private lazy var FirstObject: VC1 =
    {
        // Instantiate View Controller
        let viewController = self.storyboard?.instantiateViewController(withIdentifier: "VC1") as! VC1

        // Add View Controller as Child View Controller
        self.addChildViewController(viewController)
        return viewController
    }()


    private lazy var SecondObject: VC2 =
    {
        // Instantiate View Controller
        let viewController = self.storyboard?.instantiateViewController(withIdentifier: "VC2") as! VC2

        // Add View Controller as Child View Controller
        self.addChildViewController(viewController)
        return viewController
    }()

Storyboard View

Simulator screen shots

ScreenShot 1 - When no object added

ScreenShot 2 - When Clicked on any button

I clicked on second So showed as

Note: I had used Toolbar with three button You can do same by adding buttons in Navigation bar , Showed you Method how to do , Depend on you that want to make use of Navigation controller or ToolBar at bottom of screen