0

我有一个小问题。在我的主视图控制器上,我有一个条形按钮,可以打开一个幻灯片菜单,这是一个使用幻灯片转换的常规视图控制器。滑动菜单有一个按钮可以打开另一个视图控制器。当新的视图控制器打开时,您可以选择取消,这会关闭当前的视图控制器。问题是,用户再次进入菜单视图,而不是主视图控制器。很高兴知道我做错了什么:)

func openSupport() {
    guard  let creditViewContoller = storyboard?.instantiateViewController(withIdentifier: "support") as? CreditViewController else { return }
    present(creditViewContoller, animated: true)
}

@IBAction func buttonSupport(_ sender: UIButton) {
    let menuView = MenuViewController()
    menuView.dismiss(animated: true, completion: nil)
    openSupport()
    print("Tap on Support")
}
4

2 回答 2

2

您可以简单地通过使用关闭视图控制器

self.dismiss(animated: true, completion: nil)
于 2019-07-03T17:26:17.057 回答
1

考虑

@IBAction func buttonSupport(_ sender: UIButton) {
    let menuView = MenuViewController()               // (1)
    menuView.dismiss(animated: true, completion: nil) // (2)
    openSupport()                                     // (3)
    print("Tap on Support")
}

这:

  1. 创造新的MenuViewController,但从不呈现它;
  2. 调用dismiss从未出现过的视图控制器;和
  3. openSupport来自此实例的调用MenuViewController(从未被驳回)。

最重要的是,您希望让呈现菜单的主视图控制器进行呈现。所以,菜单视图控制器应该:

  1. 为其定义一个协议,以通知呈现视图控制器转换到下一个场景:

    protocol MenuViewControllerDelegate: class {
        func menu(_ menu: MenuViewController, present viewController: UIViewController)
    }
    
  2. 然后菜单视图控制器可以在它完成关闭时告诉它的委托它应该呈现什么:

    class MenuViewController: UIViewController {
        weak var delegate: MenuViewControllerDelegate?
    
        @IBAction func didTapSupport(_ sender: Any) {
            dismiss(animated: true) {
                guard let controller = self.storyboard?.instantiateViewController(withIdentifier: "support") else { return }
                self.delegate?.menu(self, present: controller)
            }
        }
    
        @IBAction func didTapCancel(_ sender: Any) {
            dismiss(animated: true)
        }
    }
    

然后主视图控制器需要

  1. 确保设置delegate菜单视图控制器的:

    class ViewController: UIViewController {
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destination = segue.destination as? MenuViewController {
                destination.delegate = self
            }
        }
    }
    

  2. 确保呈现菜单控制器要求的视图控制器:

    extension ViewController: MenuViewControllerDelegate {
        func menu(_ menu: MenuViewController, present viewController: UIViewController) {
            present(viewController, animated: true)
        }
    }
    

有很多不同的方法可以实现这一点,所以不要迷失在这里的细节。但想法是有一些系统,菜单视图控制器可以通过该系统请求任何要呈现support视图的人这样做,而不是尝试自己去做。

于 2019-07-03T20:52:10.967 回答