Chris_1983_Norway
Chris_1983_Norway

Reputation: 399

Return to previous ViewController when using UITabBarController but not UINavigationController

Im using a UITabBarController that I've created programatically to present UIViewControllers that I've created in Storyboard. I present these with

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// create tab one
let tabOne = storyboard.instantiateViewController(withIdentifier: "feedVC")
let tabOneBarItem = UITabBarItem(title: "feed", image: UIImage(named: "feed_icon"), selectedImage: UIImage(named: "feed_icon_selected"))
        tabOne.tabBarItem = tabOneBarItem

self.viewControllers = [tabOne]

in one of the tabs where I don't show the TabBar, I have a cancel button in the top left. I prefer this to send the user back to the previous ViewController. But settle with a specific one. The code below works, but the TabBarController do not show... what is the most efficient way to implement a cancel/return button.

Should I use UINavigationController - or are there better alternatives?

@IBAction func cancelBtnWasPressed(_ sender: Any) {
    let returnVC = storyboard?.instantiateViewController(withIdentifier: "feedVC")


    present(returnVC!, animated: true, completion: nil)


}

Upvotes: 1

Views: 366

Answers (2)

Chris_1983_Norway
Chris_1983_Norway

Reputation: 399

I found the solution that worked for me.

Swift 4:

self.tabBarController?.selectedIndex = 0

This moves the view back to the first of the Tabs i the TabBarController

Upvotes: 1

Vini App
Vini App

Reputation: 7485

You have to dismiss the current one :

@IBAction func cancelBtnWasPressed(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}

Upvotes: 0

Related Questions