简体   繁体   中英

Wrong target when calling method in custom UINavigationController from UIViewController

I created a subclass of UINavigationController and put a UIBarButtonItem in the navigation bar. The code is as follows:

SharedNavigationController.swift

func showNextButton(nc: UINavigationController) {
    print(nc)
    let nextButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Plain, target: nc, action: "next")
    print(nextButton.target)
    self.navigationBar.topItem?.rightBarButtonItem = nextButton
}

However, I am having problems with the button having the wrong target when it is tapped. Instead of the target being the navigation controller (the class in which it is created), it is instead the current view controller in the navigation controller. As a result, I get the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[App.SignupBasicInfoForm next]: unrecognized selector sent to instance 0x7af7d0c0'

I initially set the target to "self" but it is referencing the view controller within the navigation controller, rather than the navigation controller itself. I also tried setting the target as self.navigationController , with the same effect. Finally, I explicitly passed the instance of SharedNavigationController to the showNextButton method, as shown in the code above. The print statements give me this:

print(nc): <App.SharedNavigationController: 0x7d41f800>
print(nextButton.target): Optional(<App.SharedNavigationController: 0x7d41f800>)

So at least in SharedNavigationController , the target is correct. But when the button is tapped from the current view controller inside the navigation controller, it seems like the target has changed. What I tried above did not work. How can I specify the correct target for the button, without having to define the method or set the bar button item from the view controller rather than the navigation controller?

you may need to override this func in your subclass to do what you want

override func pushViewController(viewController: UIViewController, animated: Bool) {
    viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Plain, target: nc, action: "next")
    super.pushViewController(viewController, animated: animated)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM