gpt4 book ai didi

swift - UIViewControllers 共享 'generic' IBAction

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:28 28 4
gpt4 key购买 nike

我有一个包含 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 但传递不同的参数(starter helpSubtitle).

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

但是:有没有办法创建一个通用的 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.
}

}

现在从此类继承您的 ViewControllers,例如:

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")
}

}

就是这样。您的 ViewControllers 都可以调用父方法。如果您仍然想使用通用的 IBAction,您也可以这样做,但我不推荐该类(class),因为您想要传递可以变化的参数。如果你想这样做,它看起来像这样:

enter image description here

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

关于swift - UIViewControllers 共享 'generic' IBAction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54019960/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com