我的整个应用程序中的 UINavigationController
中都有一个自定义后退按钮,如下所示:
我有一个全局函数(在一个随机的 Swift 文件中;不在一个类中),我在任何需要的地方引用它:
func customBackButton(controller: UIViewController){
if !iPad(){
controller.navigationItem.leftBarButtonItem =
UIBarButtonItem(image:UIImage(named: "back"), style:.Plain, target:controller, action:"goBack")
}
}
然后在我的 Controller 的 viewDidLoad
中,我只需调用:
override func viewDidLoad() {
//...
customBackButton(self)
}
action
选择器调用我在每个使用自定义后退按钮的 Controller 中定义的 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))
}
}
关于ios - UINavigationController 和 Swift 2.2 选择器中的自定义后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38927784/