簡體   English   中英

設置導航欄背景圖片

[英]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)

但不起作用。 這是錯誤代碼。

線程 1:致命錯誤:在展開可選值時意外發現 nil

試試這段代碼,看看你的代碼在哪里崩潰了……它的起點……然后解決那部分的 nil……在你的代碼中, 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")
}

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
}

如果您使用按鈕操作集 function 調用 controller 來顯示導航 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)

就這樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM