[英]self.presentingViewController presentViewController not working
[英]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
。 PopupViewController
的presentingViewController
应该是您的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.