如何在弹出窗口关闭时在主视图控制器中以 swift 运行代码



我目前正在编写我的第一个 swift 应用程序。 目前有一个视图/视图控制器在应用程序运行时加载,以及一个绑定到单独视图控制器的弹出窗口(如下所示:https://www.youtube.com/watch?v=S5i8n_bqblE(。当我关闭弹出窗口时,我想更新原始视图上的一些内容并运行一些代码。但是,func viewDidLoad(( 和 func viewDidAppear(( 似乎都没有运行。而且我无法从弹出视图中执行任何操作,因为我无法访问主视图控制器中的组件。我该怎么办?

弹出窗口是"模态呈现",如果这有什么不同?

我假设你有一个MainViewController,你从中展示PopupVC。可以在此处使用委托模式。
定义一个弹出窗口VCDelegate,如下所示

protocol PopupVCDelegate {
func popupDidDisappear()
}

在弹出窗口VC中定义类型为PopupVCDelegatedelegate属性。在closePopup方法中,调用委托方法popupDidDisappear

class PopupVC: UIViewController {
public var delegate: PopupVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func closePopup(_ sender: Any) {
dismiss(animated: true, completion: nil)
delegate?.popupDidDisappear()
}
}

现在,任何采用此delegate的类都将能够在调用closePopup时接收回调。因此,请让您的 MainViewController 采用此委托。

class MainViewController: UIViewController, PopupVCDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
func showPopup() {
let popupViewController = //Instantiate your popup view controller
popupViewController.delegate = self
//present your popup
}
func popupDidDisappear() {
//This method will be called when the popup is closed
}
}

另一种方法是通过NSNotificationCenteronclosePopup触发通知,并在 MainViewController 中添加观察者来侦听该通知。但在这种情况下不建议这样做。

编辑

正如您所要求的NSNotificationCenter方法一样。请按如下方式更改您的课程

class PopupVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func closePopup(_ sender: Any) {
dismiss(animated: true, completion: nil)
NotificationCenter.default.post(name: NSNotification.Name("notificationClosedPopup"), object: nil)
}
}  
class MainViewController: UIViewController, PopupVCDelegate {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(onPopupClosed), name: NSNotification.Name(rawValue: "notificationClosedPopup"), object: nil)
}
@objc func onPopupClosed() {
//This method will be called when the popup is closed
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "notificationClosedPopup"), object: nil)
}
}

最新更新