Reputation: 43
This is my code:
let logo = UIImage(named: "navigationbar")
self.navigationController!.navigationBar.setBackgroundImage(logo!.resizableImage(withCapInsets: UIEdgeInsets(top: 0,left: 0, bottom: 0 ,right: 0), resizingMode: .stretch), for: .default)
But doesn't working. This is error code.
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Upvotes: 2
Views: 1243
Reputation: 5628
Your controller is definitely not a navigation controller, if it is the first controller that you present in your app you must set it in scene delegate under willConnectTo function like this:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
window?.makeKeyAndVisible()
let controller = UINavigationController(rootViewController: ViewController())
window?.rootViewController = controller
}
if you call the controller with a button action set function that present navigation Controller like this:
@objc fileprivate func callNavigationController() {
let controller = UINavigationController(rootViewController: YourController())
controller.modalPresentationStyle = .fullScreen
present(controller, animated: true, completion: nil)
}
now in viewDidLoad set the navigationBar background, first unwrap image with a guard let statement:
guard let logo = UIImage(named: "navigationbar") else { return }
after set navigation bar background image:
navigationController?.navigationBar.setBackgroundImage(logo.resizableImage(withCapInsets: UIEdgeInsets(top: 0,left: 0, bottom: 0 ,right: 0), resizingMode: .stretch), for: .default)
And that's all
Upvotes: 1
Reputation: 14397
Try this code to see where your code is crashing .... its starting point .. then solve that part whose nil ... in your code either navigationController
or Image
is nil
if let logo = UIImage(named: "navigationbar") {
if let navigation = self.navigationController {
navigation.navigationBar.setBackgroundImage(logo!.resizableImage(withCapInsets: UIEdgeInsets(top: 0,left: 0, bottom: 0 ,right: 0), resizingMode: .stretch), for: .default)
}else {
print("Navigation cotroller not found and its nil")
}
} else {
print("problem wiyh image file")
}
Upvotes: 2