简体   繁体   English

Swift 4-无法调用委托方法

[英]Swift 4 - Can't call delegate method

I have one delegate method defined in one viewController like so: 我在一个viewController定义了一个delegate方法, viewController所示:

import UIKit

protocol PatientsUserDelegate: NSObjectProtocol {

    func patientsUserDelegateMethod()

}

class PatientsUserController: UIViewController {

    var patientsUserDelegate: PatientsUserDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        print("Here")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func nextButtonPressed(_ sender: Any) {

        patientsUserDelegate?.patientsUserDelegateMethod()

    }

}

What I am trying to do is call this delegate method in another viewController like so: 我想做的是在另一个viewController调用此委托方法, viewController所示:

class PatientsRegistration: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, PatientsUserDelegate {

   var patientsUserController = PatientsUserController()

    override func viewDidLoad() {

         patientsUserController.patientsUserDelegate = self

    }

    func patientsUserDelegateMethod() {
        print("Here")
    }

}

nextButtonPressed gets called but not the delegate method is not being called in the first viewController I have. 在我拥有的第一个viewController中, viewController被调用,但未调用委托方法。 What am I doing wrong? 我究竟做错了什么?

The problem is this line: 问题是这一行:

var patientsUserController = PatientsUserController()

The trouble is that this is not the same PatientsUserController that you actually want to talk to. 问题在于这与您实际要交谈的PatientUserController不同。 It is a new PatientsUserController, a different one, that just floats in mid-air, with no relation to your running program. 它是一个新的PatientUserController,与众不同,它只是漂浮在空中,与正在运行的程序无关。 Thus, when you set the delegate... 因此,当您设置代表时...

patientsUserController.patientsUserDelegate = self

...you have set the delegate of the wrong PatientsUserController. ...您设置了错误的PatientUserController的委托。

This is such a common beginner mistake that I've written a blog post about it: 这是一个常见的初学者错误,我为此写了一篇博客文章:

http://www.programmingios.net/dont-make-a-new-instance-by-mistake/ http://www.programmingios.net/dont-make-a-new-instance-by-mistake/

As you'll see when you read that post, you need to get yourself a reference to the real PatientsUserController, the one that is already existing in your view controller hierarchy. 正如您在阅读该文章时所看到的那样,您需要获得对真实的 PatientsUserController的引用,该引用已存在于视图控制器层次结构中。 How you do that depends on the relationship between your various view controllers. 如何执行取决于各个视图控制器之间的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM