kdgwill
kdgwill

Reputation: 2199

Setting up the back button in navigation controller

I seem to be unable to correctly set up the back button of the navigationController programmatically that shows when a previous view uses

self.navigationController?.pushViewController(newView, animated: true)

I hide all of the views from the previous view in it's viewDidDisappear using a loop and in the new view presented in the viewDidAppear I attempt to set the action of the back button in various ways; however, while I can succeed in manipulating the back button that is automatically shown such as hiding it or changing it's image I am unable to set up it's action.

Any insight would be appreciated as none of the answers I have found seem to work correctly. Also this is done without any use of the storyboard

if let img = UIImage(named: "backButton") {
                self.navigationController?.navigationBar.backIndicatorImage = img
                self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = img
                print("IMAGE")
            }
            topItem.backBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Rewind, target: self,
                                                        action:#selector(self.backButtonAction(_:)))

Upvotes: 2

Views: 3108

Answers (1)

Suresh Kumar Durairaj
Suresh Kumar Durairaj

Reputation: 2126

In your case add a custom button on the Navigation.

class YourViewController: UIViewController {
//Navigation Items.

//left bar button item.
private var leftBarButtonItem : UIBarButtonItem!

//left button.
private var navigationLeftButton : UIButton!

//Your other variable/object declaration.

  func viewDidLoad() {
    super.viewDidLoad()
    self.leftBarButtonItem = UIBarButtonItem()
  }

  func viewDidAppear(animated: Bool) {
      super.viewDidAppear(animated)

      self.setNavigationBackButton()
  }



  private func setNavigationBackButton() {

    if(self.navigationLeftButton == nil) {
        self.navigationLeftButton = UIButton(type: UIButtonType.System)
    }


    //Styling your navigationLeftButton goes here...

    self.navigationLeftButton.addTarget(self, action: Selector("backButtonTapped"), forControlEvents: UIControlEvents.TouchUpInside)
    self.leftBarButtonItem.customView = self.navigationLeftButton
    self.navigationItem.leftBarButtonItem = self.leftBarButtonItem
  }

  func backButtonTapped(AnyObject:sender) {
   // Here add your custom functionalities.
   // Note, this will not pop to previous viewcontroller,

  }
}

Upvotes: 2

Related Questions