设置导航栏背景图片

Set navigation bar background image

这是我的代码:

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)

但是不起作用。这是错误代码。

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

试试这个代码看看你的代码在哪里崩溃....它的起点..然后解决那个零的部分...在你的代码中 navigationControllerImage 是 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")
}

您的控制器肯定不是导航控制器,如果它是您在应用中出现的第一个控制器,您必须在 willConnectTo 函数下的场景委托中设置它,如下所示:

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
}

如果您调用带有按钮操作集函数的控制器,显示导航控制器,如下所示:

@objc fileprivate func callNavigationController() {
let controller = UINavigationController(rootViewController: YourController())
controller.modalPresentationStyle = .fullScreen
present(controller, animated: true, completion: nil)
}

现在在viewDidLoad中设置navigationBar背景, 首先使用 guard let 语句展开图像:

guard let logo = UIImage(named: "navigationbar") else { return }

设置导航栏背景图片后:

navigationController?.navigationBar.setBackgroundImage(logo.resizableImage(withCapInsets: UIEdgeInsets(top: 0,left: 0, bottom: 0 ,right: 0), resizingMode: .stretch), for: .default)

就这些了