Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 558
Fabian Boulegue Avatar asked Nov 15 '15 08:11

Fabian Boulegue


People also ask

How do I add a navigation bar button in Swift?

You need to open the storyboard, delete the view controller that you have, press cmd , shift , l , and then search for navigation controller . Drag that onto the storyboard. You now need to click on the navigation controller and set it to be the is initial view controller under the attributes inspector .


1 Answers

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) 
like image 58
nsinvocation Avatar answered Oct 14 '22 05:10

nsinvocation