![](/img/trans.png)
[英]When user tap push notification, what is the best way to close current viewcontroller and open new viewcontroller
[英]Swift 3 - Close current ViewController and Open new ViewController
我已经浏览了一些关于此的 SO 帖子,但没有一个明确说明如何在 Swift 3 中完成此操作。
简单地说,我需要关闭当前显示的视图并打开一个新的视图控制器。 这样唯一打开的视图控制器将是第二个 VC
这是我尝试使用的代码,但是当我尝试使用此代码时,视图控制器将关闭而其余代码未执行
//Close current VC
self.dismiss(animated: true, completion: nil)
//Open the new VC
let mainStoryboard: UIStoryboard = UIStoryboard(name:"Main",bundle:Bundle.main)
let secondViewController: SecondViewController = mainStoryboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)
有人可以帮我吗? 我只需要从第 1 个 VC 到第 2 个 VC 的简单过渡并关闭第 1 个 VC。
问题是,“self”不能呈现新的 ViewController,因为它是被解雇的 ViewController。
你可以尝试调用self.presentingViewController?.present(secondViewController, animated: true, completion: nil)
花了一整天后,我在 Apple 的开发者网站上找到了一个解决方案(在这个链接上)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyboard.instantiateViewController(identifier: "second_view_controller")
secondVC.modalPresentationStyle = .fullScreen
secondVC.modalTransitionStyle = .crossDissolve
present(secondVC, animated: true, completion: nil)
如果您从某个视图控制器呈现该视图控制器,或者它是来自导航或选项卡视图控制器的视图控制器,则尝试获取最后一个可见的视图控制器,代码在此链接中
在 AppDelegate.m 中获取当前显示在屏幕上的 UIViewController
或者使用此代码(我已从该链接复制)
public extension UIWindow {
public var visibleViewController: UIViewController? {
return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
}
public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
if let nc = vc as? UINavigationController {
return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
} else if let tc = vc as? UITabBarController {
return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
} else {
if let pvc = vc?.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(pvc)
} else {
return vc
}
}
}
}
然后从该 visibleViewController 展示您的视图控制器 -
//关闭当前VC
self.dismiss(animated: true, completion: nil)
//打开新的VC
let mainStoryboard: UIStoryboard = UIStoryboard(name:"Main",bundle:Bundle.main)
let secondViewController: SecondViewController = mainStoryboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
window?.visibleViewController?.present(secondViewController, animated: true, completion: nil)
如果您的视图控制器是根视图控制器,则将其设置为根视图控制器
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = secondViewController
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.