Search code examples
iosswiftuinavigationbar

Create NavBar programmatically with Button and Title Swift


I try to create a NavBar, so far the NavBar is no problem but when I try to add the buttons and title, they don't get displayed

My NavBar look like

let NameHeight = screenHeight * 0.09
let NameWidth = screenWidth
let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: NameWidth, height: NameHeight))
self.view.addSubview(navBar)

so i try to set my NavBar title like

navigationBar.topItem.title = "some title"
or
navigationBar.title = "some title"

but both fail.
Also if i try to set a button

let btnName = UIButton()
btnName.setImage(UIImage(named: "imagename"), forState: .Normal)
btnName.frame = CGRectMake(0, 0, 30, 30)
btnName.addTarget(self, action: Selector("action"), forControlEvents: .TouchUpInside)

//.... Set Right/Left Bar Button item
let rightBarButton = UIBarButtonItem()
rightBarButton.customView = btnName
self.navigationItem.rightBarButtonItem = rightBarButton

this does not give me a error but the button is simply not displayed


Solution

  • Updated for Swift 5

    Create a navigation item instance and set title and right/left buttons to it. After navigation item is configured add it to the navigation bar.

    let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 44))
    view.addSubview(navBar)
    
    let navItem = UINavigationItem(title: "SomeTitle")
    let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(selectorName:))
    navItem.rightBarButtonItem = doneItem
    
    navBar.setItems([navItem], animated: false)