繁体   English   中英

presentingViewController不起作用

[英]presentingViewController not working

当我关闭弹出的ViewController时,我想在显示的ViewController上调用一个方法。 我像这样从“ MainViewController”启动Popup :(在EzPopup Library的帮助下,但我认为这里无关紧要)

@IBAction func onStartWorkout(_ sender: UIButton) {

    let startWorkoutVC = storyboard!.instantiateViewController(withIdentifier: "CardContent") as! StartWorkout_ViewController

    let popupVC = PopupViewController(contentController: startWorkoutVC, popupWidth: 300, popupHeight: 500)
    popupVC.cornerRadius = 10

    present(popupVC, animated: true)
}

然后当我关闭弹出窗口时,我这样做:

func dissmissPopup()  {
    if let presenter = presentingViewController as? MainViewController {
        presenter.startWorkout(index: 0, isSNR: true)
    }
    self.dismiss(animated: true, completion: nil)
}

但是不会调用该方法。 presentingViewController如何工作,为什么我对MainViewController的引用不起作用?

假设dissmissPopup在您的StartWorkout_ViewController类中,则presentingViewController将为nil因为您没有呈现StartWorkout_ViewController ,而是呈现PopupViewController PopupViewControllerpresentingViewController应该是您的MainViewController

根据PopupViewController的编写方式,您应该能够通过访问parent (给您PopupViewController ,然后访问其presentingViewController来获取所需的内容。

func dissmissPopup()  {
    if let presenter = parent?.presentingViewController as? MainViewController {
        presenter.startWorkout(index: 0, isSNR: true)
    }

    self.dismiss(animated: true, completion: nil)
}

现在,说完所有这些,就不要这样做。 这是一个糟糕的,脆弱的设计。 您正在将MainViewController需要调用某些特定方法的知识硬编码到StartWorkout_ViewController

正确的解决方案是定义协议和委托。 然后StartWorkout_ViewController只需在其委托上调用协议方法即可(不必关心它的真实身份)。 MainViewController将自己设置为StartWorkout_ViewController的委托,并实现协议的方法。

这种方法消除了StartWorkout_ViewController知道谁展示它或如何展示它的需要。 它消除了StartWorkout_ViewController知道专门调用名为startWorkout的方法的需要。 它还允许其他类呈现MainViewController并在关闭它时执行所需的任何操作,而无需对MainViewController进行进一步的硬编码更改。

这是使用协议和委托来实现的粗略概述:

StartWorkout_ViewController.swift:

protocol StartWorkoutDelegate: class {
    func complete() // add any necessary parameters
}

class StartWorkout_ViewController: UIViewController {
    weak var delegate: StartWorkoutDelegate?

    func dissmissPopup()  {
        delegate?.complete() // add any necessary parameters

        self.dismiss(animated: true, completion: nil)
    }
}

MainViewController.swift:

class MainViewController: UIViewController, StartWorkoutDelegate {
    @IBAction func onStartWorkout(_ sender: UIButton) {
        let startWorkoutVC = storyboard!.instantiateViewController(withIdentifier: "CardContent") as! StartWorkout_ViewController
        startWorkoutVC.delegate = self

        let popupVC = PopupViewController(contentController: startWorkoutVC, popupWidth: 300, popupHeight: 500)
        popupVC.cornerRadius = 10

        present(popupVC, animated: true)
    }

    func complete() {
        startWorkout() // add any necessary parameters
    }
}

暂无
暂无

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

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