1

I'm looking to add a UINavigationBar in a UIViewController. I know that I can add a navigation bar in Storyboard and I can also trigger it using a segue and also doing it manually by adding a width and height. Instead of doing it manually, I want to do it inside of the class without adding the height and width. The navigation bar behaves naturally as if it is triggered by a segue. So something like self.navigationController would work. self.navigationController would present the UINavigationBar

And any other in I need to add.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
SwiftER
  • 1,235
  • 4
  • 17
  • 40

1 Answers1

0

use this code for swift2.X for swift3 use this link Adding Navigation Bar programmatically iOS

 // Create the navigation bar
    let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 44)) // Offset by 20 pixels vertically to take the status bar into account

    navigationBar.backgroundColor = UIColor.whiteColor()
    navigationBar.delegate = self;

    // Create a navigation item with a title
    let navigationItem = UINavigationItem()
    navigationItem.title = "Title"

    // Create left and right button for navigation item
    let leftButton =  UIBarButtonItem(title: "Save", style:   UIBarButtonItemStyle.Plain, target: self, action: "btn_clicked:")
    let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil)

    // Create two buttons for the navigation item
    navigationItem.leftBarButtonItem = leftButton
    navigationItem.rightBarButtonItem = rightButton

    // Assign the navigation item to the navigation bar
    navigationBar.items = [navigationItem]

    // Make the navigation bar a subview of the current view controller
    self.view.addSubview(navigationBar)


  func btn_clicked(sender: UIBarButtonItem) {
  // Do something
 }
Community
  • 1
  • 1
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51
  • although this work the issues come with device rotation. even though I can use constraints using bar barItems and title constraints become another issue. – SwiftER Sep 21 '16 at 18:43
  • This should be possible because it can be added it by dragging it in user interface but i wanted to do it programatically. – SwiftER Sep 21 '16 at 18:47