SwiftDeveloper
SwiftDeveloper

Reputation: 7368

How to go "without navigation bar view controller" to "with navigation bar view controller" in Swift

I have project and it has many view controllers , e.g. StartViewController (Has Navigation Bar). Also processViewController and processViewController has many views and processViewController doesn't have Navigation Bar .

processViewController has Close button and action with;

@IBAction func goStart(sender: UIButton) {
    let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("StartViewController") as! StartViewController
    self.navigationController?.pushViewController(secondViewController, animated: true)
}

When I push it then;

navigationController!.navigationBar.barTintColor = UIColorFromRGBs(0x000000)
navigationController!.navigationBar.tintColor = UIColor.whiteColor();

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 164, height: 38))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "logo")
imageView.image = image
navigationItem.titleView = imageView

Those lines give error.

How can I fix it ? How can I go from without navigation bar view controller to with navigation bar view controller?

Upvotes: 3

Views: 7059

Answers (2)

pedrouan
pedrouan

Reputation: 12910

The only way how you can go from the view controller without navigation bar to view controller with one, is to present it modally.

So when you are creating that view controller, that you want to present in it's parent view controller, embed this target controller in navigation controller and then present that navigation controller, that contains your target view controller.

Swift 3

let targetViewController = UIViewController() // this is that controller, that you want to be embedded in navigation controller
let targetNavigationController = UINavigationController(rootViewController: targetViewController)
        
self.present(targetNavigationController, animated: true, completion: nil)

Upvotes: 8

Ketan Parmar
Ketan Parmar

Reputation: 27438

That because you are trying to getting navigationController or navigationBar in class or viewcontroller which is not embed with navigation controller. So you will get nil as navigationbar or navigationController so that you can't set it's property because it is nil or not exist for current viewcontroller.

Manage this things in your viewcontroller that have navigation controller embed!

Upvotes: 1

Related Questions