0

In order to perform some verifications when the back button is pushed on a UINavigationController. I decided, after searching the net on how to do that, to subclass UINavigationController and implement the UINavigationBarDelegate.

Here is my problem: as long as I do not actually implement anything of the UINavigationBarDelegate protocol it all works as when I was using a plain UINavigationController. But when I implement only this function:

    func navigationBar(_ navigationBar: UINavigationBar,
                   shouldPop item: UINavigationItem) -> Bool {
        print(#function)
        return true
    }

I can see in the debugging console that the function is actually called. But the pop does not happen, only the back button vanishes, the view stays there. I expect that with only the function above it should still work as before (i.e. the view should pop out normally).

Anyone can see the thing I am missing?

2 Answers 2

1

You are missing to pop view controller add one more line self.popViewController(animated: true) in your code

func navigationBar(_ navigationBar: UINavigationBar,
                       shouldPop item: UINavigationItem) -> Bool {
    print(#function)
    self.popViewController(animated: true)
    return true
}
Sign up to request clarification or add additional context in comments.

1 Comment

In Objective-C, it was possible to call super.navigationBar.shouldPopItem, which resumed the normal pop functionality. That seems like the ideal approach. However, it looks like a bug in Swift prevents this (bugs.swift.org/browse/SR-13788), so I'm using this approach of popping directly and returning true as a workaround.
0

You can create a back button and add the code below in the action of this button that will call the previous view as if it were the back of navigationbar. Within the action of this button you can add the actions that you want to, if you have any questions retone me.Hide button must be called in viewDidLoad()

// Action    
self.navigationController?.popViewController(animated: true)

// Hide backbutton
self.navigationController?.navigationItem.hidesBackButton = true

1 Comment

The idea of creating a new back button (as you suggest) is actually the first thing I read, when starting to search for a solution. But after reading a few more post on the subject, I got the impression that it was much better to use UINavigationBarDelegate and control the behavior of the button already there rather than making a new one. This is why I am now looking into that direction. You obviously have a different approach. At this point I cannot say which way is better. It may well be yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.