UINavigationController popToRootViewController met

2019-09-19 10:11发布

I have a UINavigationController which works great. Each view controller has its own button that pops the stack back to its root which also works great. However, I'd like to also be able to pop the stack back to its root by pressing a button on the tab bar (which is obviously in an entirely different class outside of the navigation stack).

Therefore, I created a delegate in the tab bar class which finds the view controller at the top of the stack and calls the method in that view controller to pop the stack back to the root. I printed something to the console to verify that the delegate is set up correctly and it is. Everything works exactly as it should, except that pressing the tab bar doesn't pop the stack back to its root.

Thoughts?

This is the view controller at the top of a UINavigationController stack

class BlankViewController202: UIViewController, MainContainerViewControllerDelegate {

    // pop to root
    func popToRoot() {
        self.navigationController?.popToRootViewController(animated: true)
        print("success")
    }

}

When this function above is called from within the view controller (when the user presses the button on the view controller itself), it pops the stack. But when this same exact method is called by a delegate from the tab bar, it doesn't pop the stack (but it does print to console so I know its hooked up properly).

This is where the button resides in the tab bar that when pressed should pop the stack back to its root

protocol MainContainerViewControllerDelegate {
    func popToRoot()
}

class MainContainerViewController: UIViewController {

    func moveToTab3(sender: UIButton!) {
        // ...
        let banana = BlankViewController202()
        self.delegate = banana
        delegate?.popToRoot()
    }

}

3条回答
何必那么认真
2楼-- · 2019-09-19 10:26

I think, you error delegate pattern. You can see again model delegate use protocol. If you use protocol, you delete line code "let banana = BlankViewController202()".

查看更多
你好瞎i
3楼-- · 2019-09-19 10:33

The problem is that BlankViewController202() makes a whole new, separate BlankViewController202 — it is not the particular BlankViewController202 that is already in the interface as part of the navigation controller interface. It is that BlankViewController202 you want to talk to.

查看更多
家丑人穷心不美
4楼-- · 2019-09-19 10:44

Just Follow some steps

1) Make one Object of UINavigationViewController in AppDelegate and you can access it with shared object of app delegate.

2) The first line of moveToTab3 will be [Appdelegate sharedObject].navigationViewControllerVariable = self.navigationViewController

3) In Your delegate method write this line

[[Appdelegate sharedObject].navigationViewControllerVariable popToRootViewController:true] 

this will work definitely :)

查看更多
登录 后发表回答