在没有导航控制器的情况下向视图控制器添加导航栏

时间:2016-06-23 23:24:53

标签: ios swift swift2 interface-builder

如何将导航栏添加到未嵌入导航控制器的视图控制器(实际上是集合视图控制器)?我尝试将导航栏拖到视图上,但它只是没有粘住。这是在斯威夫特。

3 个答案:

答案 0 :(得分:4)

尝试将此代码放入viewDidLoad

let height: CGFloat = 75
let navbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: height))
navbar.backgroundColor = UIColor.whiteColor()
navbar.delegate = self

let navItem = UINavigationItem()
navItem.title = "Title"
navItem.leftBarButtonItem = UIBarButtonItem(title: "Left Button", style: .Plain, target: self, action: nil)
navItem.rightBarButtonItem = UIBarButtonItem(title: "Right Button", style: .Plain, target: self, action: nil)

navbar.items = [navItem]

view.addSubview(navbar)

collectionView?.frame = CGRect(x: 0, y: height, width: UIScreen.mainScreen().bounds.width, height: (UIScreen.mainScreen().bounds.height - height))

height当然可以是你想要的任何东西。 UIBarButton的动作是你想要的任何函数的选择器。 (你也根本不需要按钮)。

<强>编辑:

  1. 调整了collectionView的框架,使其不会与UINavigationBar重叠。
  2. 将高度设为常数,以便可以在一个地方更改所有引用。

答案 1 :(得分:0)

Swift 4的更新答案:

 private func addNavigationBar(){
        let height: CGFloat = 75
        let statusBarHeight = UIApplication.shared.statusBarFrame.height;
        let navbar = UINavigationBar(frame: CGRect(x: 0, y: statusBarHeight, width: UIScreen.main.bounds.width, height: height))
        navbar.backgroundColor = UIColor.white
        navbar.delegate = self as? UINavigationBarDelegate

        let navItem = UINavigationItem()
        navItem.title = "Sensor Data"
        navItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(dismissViewController))

        navbar.items = [navItem]

        view.addSubview(navbar)

        self.view?.frame = CGRect(x: 0, y: height, width: UIScreen.main.bounds.width, height: (UIScreen.main.bounds.height - height))
    }

答案 2 :(得分:0)

这里是 swift 5 的版本。

class ViewController: UIViewController, UINavigationBarDelegate {


override func viewDidLoad() {
    super.viewDidLoad()
    
    view.addSubview(toolbar)
    toolbar.delegate = self
    
    let height: CGFloat = 75
    let navbar = UINavigationBar(frame: CGRect(x: 20, y: 20, width: UIScreen.main.bounds.width, height: height))
    navbar.backgroundColor = UIColor.white
    navbar.delegate = self

    let navItem = UINavigationItem()
    navItem.title = "Title"
    navItem.leftBarButtonItem = UIBarButtonItem(title: "Left Button", style: .plain, target: self, action: nil)
    navItem.rightBarButtonItem = UIBarButtonItem(title: "Right Button", style: .plain, target: self, action: nil)

    navbar.items = [navItem]

    view.addSubview(navbar)

    self.view.frame = CGRect(x: 0, y: height, width: UIScreen.main.bounds.width, height: (UIScreen.main.bounds.height - height))
    
}

}