【问题标题】:Set navigation bar background image设置导航栏背景图片
【发布时间】:2020-05-16 15:22:07
【问题描述】:

这是我的代码:

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 可选值

【问题讨论】:

    标签: ios swift swift4 navigationbar


    【解决方案1】:

    试试这段代码,看看你的代码在哪里崩溃......它的起点......然后解决你的代码中的 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")
    }
    

    【讨论】:

    • 哦酷。打印“未找到导航控制器且其为零”。我是初学者:((
    • 现在你需要检查为什么它为零
    • 为此您需要发布代码...您在哪里添加它?
    • 我在 viewDidLoad() 函数中添加了您的代码。但我不知道如何检查它为什么为零。我应该导入导航栏吗?
    • 您的控制器在导航控制器中?
    【解决方案2】:

    您的控制器绝对不是导航控制器,如果它是您在应用程序中出现的第一个控制器,您必须在 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)
    

    仅此而已

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多