![](/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.