Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add navigation bar to a view controller without a navigation controller

How do you add a navigation bar to a view controller (collection view controller, actually) that is not embedded in a navigation controller? I tried dragging a Navigation Bar onto the view, but it's just not sticking. This is in Swift.

like image 596
Prabhu Avatar asked Jun 23 '16 23:06

Prabhu


1 Answers

Try putting this code in your 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 can, of course, be anything you want. And the actions for the UIBarButtons are selectors to whatever function you want. (You also don't need to have buttons at all).

Edits:

  1. Adjusted the collectionView's frame so it would not overlap with UINavigationBar.
  2. Made height a constant so all its references can be changed in one place.
like image 162
Ike10 Avatar answered Nov 08 '22 23:11

Ike10