I have a custom back button in my UINavigationController
s throughout my app that looks like this:
I have a global function (in a random Swift file; not in a class) that I reference everywhere I need one:
func customBackButton(controller: UIViewController){
if !iPad(){
controller.navigationItem.leftBarButtonItem =
UIBarButtonItem(image:UIImage(named: "back"), style:.Plain, target:controller, action:"goBack")
}
}
Then in the viewDidLoad
of my controllers, I simply call:
override func viewDidLoad() {
//...
customBackButton(self)
}
The action
selector calls the goBack
function which I have defined in every controller that uses a custom back button:
func goBack(){
//Because of the splitViewController, we have to reference the main nav controller
if let navController = splitViewController?.viewControllers[0] as? UINavigationController{
navController.popViewControllerAnimated(true)
}
}
If you are shaking your head at this implementation, I am wide open to better ways of doing this. :)
Now on to my question...
How do I use the new Swift 2.2 selector syntax to reference goBack
like this?
func customBackButton(controller: UIViewController){
if !iPad(){
controller.navigationItem.leftBarButtonItem =
UIBarButtonItem(image:UIImage(named: "back"), style:.Plain, target:controller, action:#selector(controller.goBack))
}
}
This throws an error because controller
is a UIViewController
that doesn't contain the goBack()
function, even though the actual instance that gets passed in does.
Any ideas?
I haven't tried yet but It should be work if you add your function in the extension of UIViewController
extension UIViewController {
func goBack(){
//Because of the splitViewController, we have to reference the main nav controller
if let navController = splitViewController?.viewControllers[0] as? UINavigationController{
navController.popViewControllerAnimated(true)
}
}
}
When you add your goBack function you should probably reach your goBack function from anywhere.
func customBackButton(controller: UIViewController){
if !iPad(){
controller.navigationItem.leftBarButtonItem =
UIBarButtonItem(image:UIImage(named: "back"), style:.Plain, target:controller, action:#selector(controller.goBack))
}
}
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.