协议委托方法不在Swift中调用
协议委托方法不被称为..
第一视图控制器代码
class ViewController: UIViewController,customDelegate { var seconviewcontroller : SecondViewController = SecondViewController() @IBOutlet weak var Label: UILabel! override func viewDidLoad() { super.viewDidLoad() seconviewcontroller.delegate = self } func didSelectData(_ result: String) { Label.text = result print("Didselect Data Call") }
第二个视图控制器代码
import UIKit protocol customDelegate: class { func didSelectData(_ result: String) } class SecondViewController: UIViewController { var delegate: customDelegate? @IBOutlet weak var secondbutton: UIButton! override func viewDidLoad() { super.viewDidLoad() } @IBAction func secondbuttonclick(_ sender: Any) { let selectedItem = "naga" delegate?.didSelectData(selectedItem) }
如何调用函数didSelectData请帮助我
所以基本上在行var seconviewcontroller : SecondViewController = SecondViewController()
是不同于你的推视图控制器实例。
你正在做一个SecondViewController
的独立实例,所以你已经完成委托自己在推挤的时候像这样的对象
let secondVCInstance = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController secondVCInstance.delegate = self self.navigationController?.pushViewController(secondVCInstance, animated: true)
注意: – 每个对象都有自己的属性
正如你已经使用segue在视图之间进行导航。 你也可以用这个例子。 我将以下内容作为代码示例,以便您可以跟踪自己以在代码中检测问题。
第一视图控制器
import UIKit class ViewController: UIViewController, SecondVCDelegate { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let secondVC = segue.destination as? SecondViewController { secondVC.delegate = self } } func didSelectData(_ result: String) { label.text = result print(result) } }
第二视图控制器
import UIKit protocol SecondVCDelegate: class { func didSelectData(_ result: String) } class SecondViewController: UIViewController { @IBOutlet weak var button: UIButton! weak var delegate: SecondVCDelegate? override func viewDidLoad() { super.viewDidLoad() } @IBAction func buttonTapped(_ sender: UIButton) { delegate?.didSelectData("My result") dismiss(animated: true, completion: nil) } }