UIViewControllers 共享 'generic' IBAction

UIViewControllers sharing 'generic' 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)
        })

    }

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

因为我不喜欢重复代码,首先我认为这个函数应该转换成更通用的东西。

但是:有没有办法创建一个通用的 IBAction,适用于每个 viewcontroller

创建一个 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.
    }

}

现在从这个 class 中继承你的 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,您也可以这样做,但我不推荐该课程,因为您想要传递可以变化的参数。如果你想这样做,它看起来像这样:

请记住,这里的 ViewController 是从基础 ViewController 继承而来的,这就是为什么它可以访问父 class 中定义的 IBActions 的原因。您所要做的就是拖动和连接。