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