Prabhu Prabhu - 5 months ago 14
Swift Question

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.

Answer

Try putting this code in your viewDidLoad:

let navbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 75))
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: "Left Button", style: .Plain, target: self, action: nil)

navbar.items = [navItem]

view.addSubview(navbar)

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).