0

I am a beginner to XCode and Swift. Currently, I have an app with a UITabBarController that is connected to three UIViewControllers: Home, Add, and Search. How would I implement a "cancel" button in the Add view controller so that it will return to the previous view once tapped?

Daniel
  • 137
  • 2
  • 11
  • Can you give more detail? When you say cancel button what do you want to do, move to home? – Woodstock Nov 15 '18 at 22:57
  • If you want to select a tab bar item programmatically check this [Stack Overflow answer](https://stackoverflow.com/questions/28099148/switch-tab-bar-programmatically-in-swift/28099341) – Francesco Deliro Nov 15 '18 at 23:00

2 Answers2

0

You need to change

self.tabBarController?.selectedIndex = // 0 home , 1 add , 2 search
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

You can memorize the previously selected tab index before a user switches to another tab by implementing shouldSelect defined in UITabBarControllerDelegate.

class MyTabBarController: UITabBarController, UITabBarControllerDelegate
{
    var previousSelectedIndex: Int?

    override func viewDidLoad() {
        ...
        tabBarController.delegate = self
    }

    func tabBarController(tabBarController: UITabBarController, shouldSelect: UIViewController) -> Bool {
        previousSelectedIndex = tabBarController.selectedIndex
        return true
    }

    func cancel() {
        if let index = previousSelectedIndex {
            self.selectedIndex = index
        }
    }
}
royh
  • 51
  • 2