整个应用中只有一个视图的导航栏

时间:2018-12-05 18:36:58

标签: ios swift uinavigationcontroller uinavigationbar uistoryboard

我的应用程序中有多个视图,而我只想在其中一个视图上使用navigationbar。...我使用了navigationcontroller,起初我正在使用此代码(当时我的应用程序是处于婴儿期,只有2次观看)

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(false, animated: animated)
    super.viewWillDisappear(animated)
}

效果很好-但是,该应用程序变得更加复杂-我有这些视图

lazy var orderedViewControllers: [UIViewController] = {
    return [self.newVc(viewController: "pageOne"),
            self.newVc(viewController: "pageTwo"),
            self.newVc(viewController: "pageThree"),
            self.newVc(viewController: "pageFour"),
            self.newVc(viewController: "activate")
    ]
}()

即使我为每个视图创建了一个自定义视图控制器,该代码也不会应用到哪里。

我认为实现此目的的方法是在每个视图中放置最上面的代码块,但对最下面的块不起作用。本质上,我的问题是如何使用NavigationController仅在一个view上创建一个条。

3 个答案:

答案 0 :(得分:1)

一个选择:使用“基本视图控制器”类处理隐藏/显示导航栏,并将“页面”子类设置为“基本”类。

import UIKit

class BaseViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }

}

class ViewController: UIViewController {

    // has buttons with
    //    Show (e.g. push)
    // segues to Settings, First, Second, Third view controllers

}

class SettingsViewController: UIViewController {

    // Settings VC is a normal UIViewController, because
    // we *want* the NavBar to remain visible

}

class FirstViewController: BaseViewController {
    @IBAction func backTapped(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
}

class SecondViewController: BaseViewController {
    @IBAction func backTapped(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
}

class ThirdViewController: BaseViewController {
    @IBAction func backTapped(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
}

答案 1 :(得分:0)

您可以使用UINavigationControllerDelegate

的这种方法
optional func navigationController(_ navigationController: UINavigationController, 
                          willShow viewController: UIViewController, 
                          animated: Bool){
     if viewController == self."desired view controller" {
        self.isNavigationBarHidden = true
    }else{
        self.isNavigationBarHidden = false 
    }
}

答案 2 :(得分:-1)

谢谢大家的支持。我已通过以下操作解决了我的问题:

  1. 我在导航控制器中放置了我唯一想拥有导航栏的视图控制器,以查看“嵌入”菜单。
  2. 我添加了自定义后退按钮。