[英]Custom Back Button in UINavigationController and Swift 2.2 Selector
在整个应用程序的UINavigationController
我有一个自定义的后退按钮,如下所示:
我有一个全局函数(在一个随机的Swift文件中;不在一个类中),在我需要的任何地方都可以引用它:
func customBackButton(controller: UIViewController){
if !iPad(){
controller.navigationItem.leftBarButtonItem =
UIBarButtonItem(image:UIImage(named: "back"), style:.Plain, target:controller, action:"goBack")
}
}
然后,在我的控制器的viewDidLoad
中,我只需调用:
override func viewDidLoad() {
//...
customBackButton(self)
}
action
选择器调用goBack
函数,该函数已在每个使用自定义后退按钮的控制器中定义:
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)
}
}
如果您对这种实现方式不满意,我愿意采取更好的方法。 :)
现在我的问题...
我如何使用新的Swift 2.2选择器语法像这样引用goBack
?
func customBackButton(controller: UIViewController){
if !iPad(){
controller.navigationItem.leftBarButtonItem =
UIBarButtonItem(image:UIImage(named: "back"), style:.Plain, target:controller, action:#selector(controller.goBack))
}
}
这将引发错误,因为controller
是不包含goBack()
函数的UIViewController
,即使传入的实际实例也是如此。
有任何想法吗?
我还没有尝试过,但是如果您在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)
}
}
}
添加goBack函数时,您可能应该从任何地方访问goBack函数。
func customBackButton(controller: UIViewController){
if !iPad(){
controller.navigationItem.leftBarButtonItem =
UIBarButtonItem(image:UIImage(named: "back"), style:.Plain, target:controller, action:#selector(controller.goBack))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.