【问题标题】:Reload main view after modal dismiss模式关闭后重新加载主视图
【发布时间】:2020-09-28 10:01:12
【问题描述】:

在我的 Xcode-App 中,可以从每个视图中打开一个模式。每个 'base' 视图都有不同的用途,有些显示表格,有些则不显示。每当模式被解除时,如何重新加载 'base' 视图?

这似乎特别棘手,因为视图具有如此不同的结构和目的。我尝试了viewWillAppearviewDidAppearviewDidLoad,但似乎都没有成功。

【问题讨论】:

  • willAppear 和 DidAppear 应该被称为 ...
  • 他们不是。我试图通过基本 VC 中的print("dismissed") 来找出答案,但没有任何反应。顺便说一句,我通过override func viewWillDisappear(_ animated: Bool) {} 关闭了模式。
  • viewWillAppear 不会被 iOS 13 模态调用(它们不是全屏的),但是您可以在模态和呈现视图之间设置一个委托系统,以在模态将或确实消失时发出通知。跨度>
  • 我将如何做到这一点,@rraphael?

标签: swift xcode uiviewcontroller modalviewcontroller


【解决方案1】:

您可以设置一个委托模式,以便您的模态视图可以通知它何时会或确实会消失。

首先你需要为你的委托创建一个协议:

protocol ModalViewControllerDelegate: class {
    func modalControllerWillDisapear(_ modal: ModalViewController)
}

那么你的模态应该有一个委托属性(最终将是呈现控制器)并在需要时触发modalControllerWillDisapear方法:

final class ModalViewController: UIViewController {
    weak var delegate: ModalViewControllerDelegate?

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        delegate?.modalControllerWillDisapear(self)
    }
}

所有将呈现模态控制器的视图控制器都必须符合该协议,并在呈现时将自己指定为模态的委托:

final class SomeViewController: UIViewController {
    private func presentModalController() {
        let modal = ModalViewController()
        modal.delegate = self
        self.present(modal, animated: true)
    }
}

extension SomeViewController: ModalViewControllerDelegate {
    func modalControllerWillDisapear(_ modal: ModalViewController) {
        // This is called when your modal will disappear. You can reload your data.
        print("reload")
    }
}

注意:如果您使用 segues 来展示您的模态,您可以在 prepare(for:sender:) 方法中分配委托属性,而不是在自定义方法中。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    switch (segue.identifier, segue.destination) {
        // Check that the segue identifer matches and destination controller is a ModalViewController
    case ("showModalSegue", let destination as ModalViewController):
        destination.delegate = self
    case _:
        break
    }
}

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 2021-07-29
    • 2020-11-22
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    相关资源
    最近更新 更多