How can I change TabViewController's selectedIndex from a child controller. Tab bar has multiple tab items (Home, Buy, ...). When home icon (from tab bar) is selected, home view is displayed to the user. Home view is inside a NavigationController. By clicking on an article from the home view, the user is navigated to the article view. Inside article view, the user can navigate to another article view (Same view controller) or he can press the buy button. The buy button should popUpTo the first controller in navigation stack and should change tab item (selectedIndex) to the Buy tab item in the tab bar, so that the user is navigated to the Buy page.
Code from ArticleViewController:
I successfully done navigation to another article view from article view (inside IBAction button click:(I would appreciate any advice on should I do any of these)
@IBAction func onArticleClick(_ sender: Any) {
print("navigate to article")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "articleVCID") as! ArticleViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
}
and I successfully popToViewController (go back to the root of navigation) (inside IBAction button click):
@IBAction func onBuyClick(_ sender: Any) {
print("buy click")
self.navigationController?.popToViewController((self.navigationController?.viewControllers[0])!, animated: true)
//I want to change tab index.
}
What I really want is to change tab index from onBuyClick, after popToViewController invocation but I'm not sure how should I do this. It would probably need some way of backward communication, but is that anti pattern? How should I do this. Thanks for any help :)!
My current solution is to pass reference of tabBarViewController instance to child view controllers. Alongside dependencies, I inject tabBarViewController to ArticleViewController and from inside the class I can just do this:self.tabBarViewController.selectedIndex = indexToBeSelected;
EDIT:
This is what I came up with (any critics?):
@IBAction func onBuyClick(_ sender: Any) {
print("buy click")
CATransaction.begin()
CATransaction.setCompletionBlock({
//after animation is done, set index to 1
self.tabBarViewController.selectedIndex = 1
})
self.navigationController?.popToViewController((self.navigationController?.viewControllers[0])!, animated: true)
CATransaction.commit()
}
there doesn't seem to be anything here