DMop
DMop

Reputation: 483

Can't Produce "< Back" on Swift Navigation bar Programmatically

Let me first begin by saying I am doing all of my coding programmatically. My problem is that I can't produce the classic iOS "<back" in my navigation bar. I suspect this is because I'm not using story boards?

This is the function I am using to create the navigation bar:

// Makes a navigation Bar
func makeNavigationBar(navigationBar: UINavigationBar, barTitle: String, forwardButton: Bool, backButton: Bool, page: UIViewController){
  // Create a navigation item with a title
  let navigationItem = UINavigationItem()
  navigationItem.title = barTitle

  // Create left navigation item
  if(backButton){
    let leftButton =  UIBarButtonItem(title: "Back", style:   UIBarButtonItemStyle.Plain, target: page, action: "backClicked:")
    // Create two buttons for the navigation item
    navigationItem.leftBarButtonItem = leftButton
  }
  if(forwardButton){
    let rightButton =  UIBarButtonItem(title: "Next", style:   UIBarButtonItemStyle.Plain, target: page, action: "nextClickedClicked:")
    // Create two buttons for the navigation item
    navigationItem.rightBarButtonItem = rightButton
  }
  // Assign the navigation item to the navigation bar
  navigationBar.items = [navigationItem]
  //Adds the bar to the view
  page.view.addSubview(navigationBar)
}

This is the call I am making to that function:

let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, height/12)) 
creationFunctions.makeNavigationBar(navigationBar, barTitle: "", forwardButton: false, backButton: true, page: self)

Here is the "backClicked" function:

func backClicked (sender: UIBarButtonItem!){
    self.dismissViewControllerAnimated(true, completion: {});
}

Thank you for your help.

Upvotes: 0

Views: 1613

Answers (1)

kamwysoc
kamwysoc

Reputation: 6859

Hi here it is code that creates custom back button and add it navigationController. I have these methods in my ViewController class.

func addBackButton() {
    let image = UIImage(named: "BackImage")!.imageWithRenderingMode(.AlwaysOriginal)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .Plain, target: self, action: "backClicked:")
}

func backClicked (sender: UIBarButtonItem!){
    self.dismissViewControllerAnimated(true, nil);
}

Hope it help you

Upvotes: 1

Related Questions