gpt4 book ai didi

ios - 自定义协议(protocol)委托(delegate)方法不调用

转载 作者:行者123 更新时间:2023-11-29 11:44:06 26 4
gpt4 key购买 nike

我正在尝试使用自定义协议(protocol)从另一个 View Controller 更改一个 View Controller 的标签,但未调用其委托(delegate)方法

ViewController3代码:

当我点击关闭按钮时,它的委托(delegate)方法没有在我的 ViewController2 中被调用。

protocol ViewController3Delegate: class {

func changeLable(_ text: String)
}

class ViewController3: UIViewController {

weak var delegate: ViewController3Delegate?

override func viewDidLoad() {
super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

@IBAction func btnCloseAction(_ sender: Any) {

delegate?.changeLable("fillter applied")
self.dismiss(animated: true, completion: nil)
}
}

ViewController2代码:

class ViewController2: UIViewController,ViewController3Delegate {

@IBOutlet weak var lblReport: UILabel!

let VC3 = ViewController3(nibName: "ViewController3", bundle: nil)

override func viewDidLoad() {

super.viewDidLoad()
VC3.delegate = self
}

func changeLable(_ text: String) {

print("delegate called")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}
}

谁知道我哪里错了,请给我一些解决方案

最佳答案

您尚未在 ViewController2 中定义委托(delegate),该委托(delegate)将用于 ViewController3 中的委托(delegate)。

看这个:

 protocol ViewController3Delegate: class {

func changeLable(_ text: String)
}

class ViewController3: UIViewController {

weak var delegate: ViewController3Delegate?

override func viewDidLoad() {
super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

@IBAction func btnCloseAction(_ sender: Any) {
if delgate !=nil {

delegate?.changeLable("fillter applied")
self.dismiss(animated: true, completion: nil)
}
}
}

然后在您的 ViewController2 类中:

    class ViewController2: UIViewController,ViewController3Delegate {

@IBOutlet weak var lblReport: UILabel!


override func viewDidLoad() {

super.viewDidLoad()
}

func changeLable(_ text: String) {

print("delegate called")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{

if segue.identifier = "Yoursegueientifier"
{
let vc = segue.destination as! ViewController3
vc.delegate = self
}
}
}

注意:您必须在 Storyboard中定义您的 segueidentifer 名称

关于ios - 自定义协议(protocol)委托(delegate)方法不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44882711/

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