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.
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 UIBarButton
s are selectors to whatever function you want. (You also don't need to have buttons at all).
Edits:
collectionView
's frame so it would not overlap with UINavigationBar
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With