Back to root view controller in swift - ios

Is there any way to dismiss all the view controllers ( in which some controllers are pushed through navigation) and go back to the root view controller. I saw lots of examples but they didn't work in my application. I am using swift 4
This is code in appdelegate
func setNavigationToRootViews(){
storyBoard = UIStoryboard(name: "Main", bundle: nil)
nav = storyBoard?.instantiateViewController(withIdentifier: "mainNavigation") as! UINavigationController?
let accessToken: String? = KeychainWrapper.standard.string(forKey: "token")
print(accessToken as Any)
if accessToken != nil {
let homeVc = storyBoard?.instantiateViewController(withIdentifier: "Home-VC") as! HomeViewController
nav?.pushViewController(homeVc, animated: false)
}else{
let welcomVc = storyBoard?.instantiateViewController(withIdentifier: "login-VC") as! LoginViewController
nav?.pushViewController(welcomVc, animated: false)
}
let leftMenuVC = storyBoard?.instantiateViewController(withIdentifier: "menu-VC") as! MenuViewController
container = MFSideMenuContainerViewController.container(withCenter: nav, leftMenuViewController: leftMenuVC, rightMenuViewController: nil)
container?.panMode = MFSideMenuPanModeNone
window?.rootViewController = container
window?.makeKeyAndVisible()
}
and this in my last View controller
#IBAction func okayBtnTapped(_ sender: Any) {
_ = self.navigationController?.popToRootViewController(animated:
true)
dismiss(animated: true, completion: nil)
}

Try this one:
self.navigationController?.popToRootViewController(animated: true)

You can just set a new RootController like this:
let storyboard = UIStoryboard(name: "sName", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "<YOUR ROOT CONTROLLER>")
self.window?.rootViewController = viewController
If you don't have a window at self.window you need to instanciate one based on your AppDelegate.
If you're within a NavigationController you can also use the answer of #Anshul Bhatheja

Check you navigation controller, and view controllers inside that navigation controller. It seems debugging issue.
this method popToRootViewController(animated:) is the method should work

If you are working with simple push navigation controller and you want to go back to root view controller then you simply have to write
_ = self.navigationController?.popToRootViewController(animated: true)

extension UINavigationController {
func popToViewController(ofClass: AnyClass, animated: Bool = true) {
if let vc = viewControllers.filter({$0.isKind(of: ofClass)}).last {
popToViewController(vc, animated: animated)
}
}
func popViewControllers(viewsToPop: Int, animated: Bool = true) {
if viewControllers.count > viewsToPop {
let vc = viewControllers[viewControllers.count - viewsToPop - 1]
popToViewController(vc, animated: animated)
}
}
}
pop to SomeViewController class
navigationController?.popToViewController(ofClass: SomeViewController.self)
pop 2 view controllers
navigationController?.popViewControllers(viewsToPop: 2)

Related

Navigation Bar disappears when going back to Home VC from a Details VC from Push Notification

If I click on the push notification, it takes me to the details page but when I click on the programatically created back button, it takes me back to HomeVC but with the top nav bar gone. Here is my app delegate function where I present the details VC :
private func gotoDetailsVC(value : String)
{
guard let window = UIApplication.shared.connectedScenes.filter({$0.activationState == .foregroundActive
|| $0.activationState == .background || $0.activationState == .foregroundInactive}).compactMap({$0 as? UIWindowScene}).first?.windows.filter({$0.isKeyWindow}).first
else { return }
let storyboard = UIStoryboard(name: "Home", bundle: nil)
let detailsVC = storyboard.instantiateViewController(identifier: "viewDeviceDataController") as viewDeviceDataController
detailsVC.deviceID = value
detailsVC.didComeFromPN = true
let navController = UINavigationController(rootViewController: detailsVC)
navController.modalPresentationStyle = .popover
// you can assign your vc directly or push it in navigation stack as follows:
window.rootViewController = navController
window.makeKeyAndVisible()
}
And here is my back button on the DetailsVC :
#objc func backAction() {
let storyboard = UIStoryboard.init(name: "Home", bundle: nil)
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
homeVC.modalPresentationStyle = .automatic
present(homeVC, animated: true, completion: nil)
}
How can I resolve this issue? Please help.
Resolved by navigating to root Navigation Controller.
#objc func backAction() {
let storyboard = UIStoryboard.init(name: "Home", bundle: nil)
let homeVC = storyboard.instantiateViewController(withIdentifier: "navControllerHome") as! UINavigationController
homeVC.modalPresentationStyle = .fullScreen
present(homeVC, animated: true, completion: nil)
}
Usually back action would just return to a previous state, but here it seems you are recreating the view.
I would not make private func gotoDetailsVC(value : String) replace rootViewController and instead make it be presented by current navigationController then on your back action you would not create a new home but dismiss your detail screen.

Presenting NavigationController with TabBarViewController can not select index programmatically

I am trying to present NavigationController and select second tab in the completion block. My code is:
let chatViewController = UITabBarController()
let navigationController = UINavigationController(rootViewController: chatViewController)
present(navigationController, animated: true, completion: {
self.visibleViewController = navigationController
self.visibleViewController?.tabBarController?.selectedIndex = 1
})
Second attempt:
let chatViewController = UITabBarController()
let navigationController = UINavigationController(rootViewController: chatViewController)
navigationController.tabBarController?.selectedIndex = 1
present(navigationController, animated: true, completion: {
self.visibleViewController = navigationController
})
In both cases tabBarController is nil. How can I switch to different tab?
You are trying to access UITabBarController of UINavigationController, but you need to access the very first controller from UINavigationController and from there you need to make your UITabBar selected like this way:
func showTabBarControllerr() {
let chatViewController = UITabBarController()
//Note: Make sure you have already added the Controllers in Tabbarcontroller
chatViewController.viewControllers = [DemoOne(), DemoTwo()]
let navigationController = UINavigationController(rootViewController: chatViewController)
present(navigationController, animated: true, completion: {
if let tabBarController = navigationController.viewControllers.first as? UITabBarController {
tabBarController.selectedIndex = 1
}
})
}
Let me know this helps or not!
Instead of calling
present(navigationController, animated: true, completion: { })
in viewDidLoad, try to call it in viewWillAppear or viewDidAppear
Try this (Swift 5):
Set an identifier to your UITabBarController in the Storyboard, something like MainTabBar
Into a function or IBAction, use this code:
let tbc = storyboard?.instantiateViewController(withIdentifier: "MainTabBar") as! UITabBarController
tbc.selectedIndex = 1 // This is the index of your controller
present(tbc, animated: false, completion: nil)

Show and dismiss View Cntrollers in swift 4

I'm trying to present a view controller and dismiss my current modal view. I saw the answers on StackOverflow, but I don't understand it.
self.dismissViewControllerAnimated(true, completion: {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("myViewController")
self.presentViewController(vc!, animated: true, completion: nil)
})
Could anyone please tell me, how to do it simply? Thanks
Check your main controller in stack and pop all other view controllers and then present new View Controller.
if let controllers = self.navigationController?.viewControllers {
for vc in controllers {
// Check if the view controller is of MainViewController type
if let myVC = vc as? MainViewController {
self.navigationController?.popToViewController(myVC, animated: false)
}
}
}
Push view controller :
let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
self.navigationController?.pushViewController(secondVC, animated: true)
or Present View Controller :
let next = self.storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
self.present(next as UIViewController, animated: true, completion: nil)
You can use this code to Present viewcontroller.
let yourVC = UIStoryboard(name: storyBord, bundle: nil).instantiateViewController(withIdentifier:ID) as! yourViewController
let navController = UINavigationController(rootViewController: yourVC)
self.present(navController, animated: true, completion: {
})
And for dissmissing use this in your presented viewController
self.dismiss(animated: true, completion: {
})

Transition to MainVC gives the empty View without subviews

I'm using this type of transition to UIViewcontroller:
self.navigationController?.popToViewController(MainVC(), animated: false)
And in result i want to receive the MainVC with all subviews... but i receive only empty main View without any subviews. What i did wrong?
Update:
I have the transition to MainVC, but it's empty, only initial View, without all subviews. What is the reason?
You should pass object of MainVC()
like below
let objOfMainVC = MainVC()
self.navigationController?.popToViewController(objOfMainVC, animated: false)
If you are using storyboard then
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let main = storyBoard.instantiateViewController(withIdentifier: "MainVC") as! MainVC // set withIdentifier to your identifier that was set in your storyboard.
self.navigationController?.pushViewController(main, animated: false)
You need the reference of MainVC. You can't just create a new instance of MainVC()
if let viewControllers = self.navigationController?.viewControllers {
for vc in viewControllers {
if let _ = vc as? MainVC {
self.navigationController?.popToViewController(vc, animated: true)
break
}
}
}
Or if your MainVC is root view controller of navigation controller.
self.navigationController?.popToRootViewController(animated: true)

Show BlurEffect on manual segue

I have a question regarding blureffects on a view controller. I program all of my segues manually for several reasons. But when I go to a viewcontroller that has a blureffect background, I only see a dark gray background. How can I solve this that the view controller blur effect lays on top of another viewcontroller where the content of the previous viewcontroller can be seen through?
The blureffects are now applied by storyboard with transparant background views.
My code for seque is:
Action:
#IBAction func ToUserSections(_ sender: Any) {
let controller =
Navigation.getDestinationViewControllerWith("User",
controllerName: "UserSectionsVC")
present(controller, animated: false, completion: nil)
}
Class:
class Navigation{
static func getDestinationViewControllerWith(_
storyboardName:String, controllerName:String)-> UIViewController{
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let controller =
storyboard.instantiateViewController(withIdentifier:
controllerName) as UIViewController
return controller
}
}
Hope you can help me with this because it will maximize aesthetics for the app :D
try this.
let viewController : CustomViewControlller = UIStoryboard.getMainStoryboard().instantiateViewController(withIdentifier: "Identifier") as! CustomViewControlller
viewController.modalPresentationStyle = .overCurrentContext
viewController.modalTransitionStyle = .crossDissolve
self.present(viewController, animated: true, completion: { _ in })
Alright for others to know, what worked for me was the following:
At IBAction: adding the following line before presenting
controller.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
Like this:
#IBAction func ToUserSections(_ sender: Any) {
let controller = Navigation.getDestinationViewControllerWith("User", controllerName: "UserSectionsVC")
controller.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
present(controller, animated: false, completion: nil)
}

Resources