Cris Monero Jr
Cris Monero Jr

Reputation: 13

There is a fatal error (for navigationbar) in Swift

I am a new programmer. I have a problem about navigation controller. There was an error:

fatal error: unexpectedly found nil while unwrapping an Optional value

My Navigation Codes (there is an error):

let color: UIColor = UIColor(red: 24.0 / 255, green: 75.0 / 255, blue: 152.0 / 255, alpha: 1)
self.navigationController!.navigationBar.translucent = false
self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController!.navigationBar.barTintColor = color
self.navigationController!.navigationBar.barStyle = .BlackTranslucent

Also I uploaded screenshots

enter image description here

enter image description here

Upvotes: 1

Views: 1152

Answers (2)

Teja Nandamuri
Teja Nandamuri

Reputation: 11201

The error says that, your navigation controller is nil. It means, your view controller didn't have any navigation controller attached to it.

You can either add a navigation controller programmatically or simply, you can go to editor-> embed in -> navigation controller in your Xcode

Note:

If you are presenting the view controller by code, make sure you present the view controller with navigation controller.

so, in your case,this code presents the Home view controller without the navigation controller.So even though your storyboard has the navigation controller, it will be nil, as you are presenting the HomeView controller only through code:

let storyboard = UIStoryboard(name: "Home", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("HomeVC")
 self.presentViewController(vc, animated: true, completion: nil)

must be:

let storyboard = UIStoryboard(name: "Home", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("HomeVCNavigation") //storyboard ID for the navigation controller HomeVCNavigation
self.presentViewController(vc, animated: true, completion: nil)

OR

Try this:

   let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("HomeVC") as! ViewController

let navController = UINavigationController(rootViewController: VC1) // Creating a navigation controller with VC1 at the root of the navigation stack.

self.presentViewController(navController, animated:true, completion: nil)

You must present the navigation controller, which already has the Home view controller in it. Change your code at here: enter image description here

enter image description here

Upvotes: 1

Adrian
Adrian

Reputation: 16715

Select the viewController from Interface Builder, then click Editor\Embed In\Navigation Controller. It appears you don't have your scene embedded in a navigation controller.

Upvotes: 1

Related Questions