UIViewControllers共享“通用” IBAction

时间:2019-01-03 09:59:31

标签: swift function viewcontroller dry ibaction

我有一个6 UIViewControllers的应用。

任何viewcontroller都具有以下功能:

@IBAction func onHelp(_ sender: UIBarButtonItem) {

        DispatchQueue.main.async(execute: { () -> Void in
            let helpVC =  self.storyboard?.instantiateViewController(withIdentifier: "Help") as! HelpViewController
            helpVC.starter = "MapHelp"
            helpVC.helpSubtitle = "Map"
            self.present(helpVC, animated: true, completion: nil)
        })

    }

任何IBAction中的任何viewcontroller都呈现相同的HelpViewController,但传递不同的参数(starterhelpSubtitle)。

由于我不喜欢重复代码,因此我首先认为应该将此函数转换为更通用的东西。

但是:有什么方法可以创建一个通用的IBAction并为每个viewcontroller工作吗?

1 个答案:

答案 0 :(得分:0)

创建一个BaseViewController并在其中添加通用方法。

class BaseViewController: UIViewController {



override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    func genericMethod(starter: String, helpSubtitle: String){
        let helpVC =  self.storyboard?.instantiateViewController(withIdentifier: "Help") as! HelpViewController
        helpVC.starter = starter
        helpVC.helpSubtitle = helpSubtitle
        self.present(helpVC, animated: true, completion: nil)
    }

    @IBAction func onHelp(_ sender: UIButton?) {
       //You can use this method as generic IBaction if you want. It can be connected to buttons of all child View Controllers. But doing so will limit your param sending ability. On the plus side though, you won't have to define an IBAction everywhere and you can simply connect your child VC's button to Parent Class' IBAction.
    }

}

现在从此类继承您的ViewController:

import UIKit

class ViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func btnTapped(_ sender: Any) {
        genericMethod(starter: "View Controller", helpSubtitle: "I was triggered from VC1")
    }

}

import UIKit

class SecondViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func btnTapped(_ sender: Any) {
        genericMethod(starter: "View Controller 2", helpSubtitle: "I was triggered from VC2")
    }

}

就是这样。您的两个ViewController都可以调用父方法。如果您仍然想使用通用的IBAction,您也可以这样做,但是鉴于您希望传递可以变化的参数,因此我不建议您这样做。但是,如果您想这样做,它将看起来像这样:

enter image description here

请记住,这里的ViewController是从基本ViewController继承的,这就是为什么它可以访问父类中定义的IBAction的原因。您所需要做的就是拖动并连接。