Josh O'Connor
Josh O'Connor

Reputation: 4962

Programmatically set navigation bar?

I am programmatically presenting a view controller, but when a view controller appears, it is missing a navigation bar. Is there any way to programmatically set a navigation bar on this new view controller when it is called?

Here is my code so far:

//LOAD CRICKET GAME
if gameGAMETYPE[index] == "Cricket" && gameGAMEPLAYERS[index] == "1" {

    println("LOAD ONE PLAYER CRICKET")
    //load OnePlayerCricket.swift
    //replace tableData with TABLEDATA

    //programatically present new view controller
    if let resultController = storyboard!.instantiateViewControllerWithIdentifier("OnePlayerCricketVC") as? OnePlayerCricket {
        presentViewController(resultController, animated: true, completion: nil)

        //programmatically present a navigation bar

         NEED HELP HERE!!!! thank you :)

}

Upvotes: 5

Views: 12947

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Here is your code for initiate navigation controller from firstView:

if let resultController = storyboard!.instantiateViewControllerWithIdentifier("OnePlayerCricketVC") as? OnePlayerCricket {
        let navController = UINavigationController(rootViewController: resultController) // Creating a navigation controller with resultController at the root of the navigation stack.
        self.presentViewController(navController, animated:true, completion: nil)
    }

EDIT:

If you wan to add back button into that navigation then use this code into OnePlayerCricket.swift class:

override func viewDidLoad() {
    super.viewDidLoad()

    let backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
    navigationItem.leftBarButtonItem = backButton

}

func goBack(){
    dismissViewControllerAnimated(true, completion: nil)
}

If you want to do all of this from firstView then here is your code:

@IBAction func btnPressed(sender: AnyObject) {


    if let resultController = storyboard!.instantiateViewControllerWithIdentifier("OnePlayerCricketVC") as? OnePlayerCricketVC {
        resultController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
        let navController = UINavigationController(rootViewController: resultController) // Creating a navigation controller with VC1 at the root of the navigation stack.
        self.presentViewController(navController, animated:true, completion: nil)
    }
}

func goBack(){
    dismissViewControllerAnimated(true, completion: nil)
}

Upvotes: 8

Related Questions