Swift 3.0委托协议不起作用

我在两个视图控制器中制作了委托协议。 但委托方法不会调用我的代码片段。 是什么原因。 我无法找到问题,请发布您的建议以重温此问题。

主视图控制器

class ViewController: UIViewController, testDelegateMethod { override func viewDidLoad() { super.viewDidLoad() let vw = testViewController() vw.delegateTest = self let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") self.navigationController?.pushViewController(push!, animated: true) } func testMethod(value:String) { print("Hai", value) } } 

子视图控制器

 protocol testDelegateMethod { func testMethod(value:String) } class testViewController: UIViewController { var delegateTest : testDelegateMethod? override func viewDidLoad() { super.viewDidLoad() } @IBAction func actSubmit(_ sender: Any) { delegateTest?.testMethod(value: "Hello how are you!") } } 

viewdidLoad()方法中更新这些更改

 override func viewDidLoad() { super.viewDidLoad() if let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") as? SelectionScreen { push.delegateTest = self } } 

由于这一行你面临的问题

 let vw = testViewController() vw.delegateTest = self 

您已经创建了testViewController vw的实例,以及vw实例的Assigned委托

在下一行

 let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") self.navigationController?.pushViewController(push!, animated: true) 

您正在创建testviewcontroller push的不同实例

不需要这个代码,

 let vw = testViewController() vw.delegateTest = self 

相反

 let push testViewController = self.storyboard.instantiateViewController(withIdentifier: "testViewController") as! testViewController push.delegateTest = self self.navigationController?.pushViewController(push, animated: true) 

这段代码片段没有意义。 您只需创建一个对象,但不会进一步使用它。 因此,请删除此代码段。

  let vw = testViewController() vw.delegateTest = self 

这样做:

 override func viewDidLoad() { super.viewDidLoad() let pushVC = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") as! testViewController pushVC.delegateTest = self self.navigationController?.pushViewController(pushVC, animated: true) } 

我想,你把代码func testMethod(value:String) { print("Hai", value) }放到viewDidLoad及上面let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") self.navigationController?.pushViewController(push!, animated: true)

 let vw = testViewController() // Your are doing wrong code vw.delegateTest = self 

仅使用此

我希望它对你有用

 let storyboard = UIStoryboard(name: "Main", bundle: nil) let push = storyboard.instantiateViewController(withIdentifier:"testViewController")as! testViewController push.delegateTest = self self.navigationController?.pushViewController(push, animated: true)