【发布时间】:2021-11-19 18:20:39
【问题描述】:
我知道这个问题在这里被问了很多,我已经阅读了所有这些问题,但我的问题仍然存在。我想在我的项目中包含委托模式,以便从一个类调用另一个类中的函数。但它也没有在那里工作。所以我创建了一个全新的项目来再次练习该模式。只有3个小时,我就是做不到。我的委托仍然留在我的主 ViewController nil 中。
这是我的 ViewController 代码。它是初始化的 ViewController 也是委托模式的主人,而 buttonViewController 是仆人:
import UIKit
protocol ViewControllerDelegate {
func printTest(message: String)
}
class ViewController: UIViewController {
var delegate: ViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func perform(_ sender: UIButton) {
let vc = storyboard?.instantiateViewController(withIdentifier: "vc") as! ButtonViewController
if delegate == nil {
print("Ist nil")
}
delegate?.printTest(message: "Test")
present(vc, animated: true, completion: nil)
}
}
如果用户按下执行按钮,我想在我的 buttonViewController 中调用一个函数,而不是我想对我的 buttonViewController 执行 segue。
这是我的 ButtonViewController:
import UIKit
class ButtonViewController: UIViewController, ViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
ViewController().delegate = self
print("test")
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@IBAction func performsegue(_ sender: UIButton) {
}
func printTest(message: String) {
print(message + "\(self)")
}
}
我已经尝试执行一个 segue,首先 viewDidLoad 由我的 ButtonViewController 调用,然后返回到 ViewController,然后通过按钮再次调用 perform 方法,然后查看 delegate 是否仍然为 nil,是的不幸的是仍然为零。
有人可以帮我解决这个问题吗?
最好的问候!
【问题讨论】:
-
查看本教程:medium.com/@astitv96/…
-
问题是
ViewController().delegate = self是个废话。它创建一个ViewController的新实例,将delegate分配给它,然后丢弃它。该实例从未使用过。 -
你为什么要在这里使用委托?据我了解,你只想在
perform中做vc.printTest(message: "Test"),所以就这样做吧! -
@Sulthan 我已经考虑过了,但即使我在 viewDidLoad 之外定义我的 ViewController 也不起作用。
-
@Sweeper 这只是一个测试,测试后我想在我的 buttonViewController 中更改图片。