Swift 4-无法调用委托方法

时间:2019-06-10 00:18:18

标签: ios swift

我在一个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()

    }

}

我想做的是像下面这样在另一个viewController中调用此委托方法:

class PatientsRegistration: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, PatientsUserDelegate {

   var patientsUserController = PatientsUserController()

    override func viewDidLoad() {

         patientsUserController.patientsUserDelegate = self

    }

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

}

nextButtonPressed被调用,但是我拥有的第一个viewController中没有调用委托方法。我在做什么错了?

1 个答案:

答案 0 :(得分:3)

问题是这一行:

var patientsUserController = PatientsUserController()

麻烦的是,这与您实际要交谈的PatientUserController不同。它是一个新的PatientUserController,与众不同,它只是漂浮在空中,与正在运行的程序无关。因此,当您设置委托时...

patientsUserController.patientsUserDelegate = self

...您设置了错误的PatientUserController的委托。

这是一个常见的初学者错误,我为此写了一篇博客文章:

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

正如您在阅读该文章时所看到的那样,您需要获得对 real PatientUserController的引用,该引用已存在于视图控制器层次结构中。如何执行取决于各个视图控制器之间的关系。