Search code examples
swiftuinavigationcontrollermodal-dialoguitabbarcontrolleruitabbar

Switch tab bar controller view controller after dismissing a modally presented view controller


In my project you can create a post from a modal view.

When the modal view is dismissed (user presses on save post) I want to switch the tab bar controller to the second tab (post feed screen).

This topic is similar to my problem. The only difference being this is presented from a modal view. I can't figure out how to implement it in my code (tab bar is nil) Switch tab bar programmatically in Swift

I have added 3 images to make this issue clearer

feature to implement

code screenshot

console message

@objc func saveAction(sender: UIButton) {
    print ("> save pressed")
    print(presentingViewController?.tabBarController)
    print(presentingViewController)
    
    presentingViewController?.tabBarController?.selectedIndex = 1
    dismiss(animated: true)
} 

edit: sorry stack overflow doesn't allow me to add images yet


Solution

  • You can do this using delegate pattern. But if you prefer not to add a delegate for this, you can do as shown below;

    You can switch the tabbar by changing the selectedIndex property of tabBarController

    if let presenter = presentingViewController as? LibraryViewController {
            presenter.tabBarController?.selectedIndex = 1
        }
    dismiss(animated: true)
    

    If you are presenting the modal on navigation controller in tabbar, use:

        if let tabBar = presentingViewController as? UITabBarController {
            tabBar.selectedIndex = 1
        }
        dismiss(animated: true)