8

My application has three viewController associated with three tab of tabBar. I want to switch from 1st tab to 3rd tab and pass some data from 1st view controller to 3rd view controller. I can't do it with segue, because segue create navigation within the selected tab. That is not my requirement. I want to switch tab in tabBar and pass some data without any navigation. How can i do it ?

Nuibb
  • 1,800
  • 2
  • 22
  • 36
  • here's a concise example to share data across controllers using a singleton Swift class: https://stackoverflow.com/a/44380145/2162226 – Gene Bo Jul 19 '17 at 21:01
  • If you at not at the tab root, you can use an unwind segue. [Here is an example.](https://stackoverflow.com/a/47751962/3681880) – Suragch Dec 11 '17 at 11:38

3 Answers3

10

Swift 3 in latest Xcode version 8.3.3

First you can set a tab bar delegate UITabBarControllerDelegate in FirstViewController. You can use this when you want to send data from one view controller to another by clicking the tab bar button in UITabBarViewController.

class FirstViewController: UIViewController ,UITabBarControllerDelegate {
    let arrayName = ["First", "Second", "Third"] 

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tabBarController?.delegate = self
    }

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        if viewController.isKind(of: FirstsubsecoundViewController.self as AnyClass) {
            let viewController  = tabBarController.viewControllers?[1] as! SecondViewController
            viewController.arrayData = self.arrayName
        } 

        return true
    }
}

Get data in SecondViewController:

class SecondViewController: UIViewController {
    var arrayData: [String] = NSArray()
    override func viewDidLoad() {
       super.viewDidLoad()
       print(arrayData) // Output: ["First", "Second", "Third"]
   }
}
Community
  • 1
  • 1
Arjun Yadav
  • 1,369
  • 1
  • 10
  • 23
4

you can use this code : Objective C

[tab setSelectedIndex:2];

save your array in NSUserDefaults like this:

[[NSUserDefaults standardUserDefaults]setObject:yourArray forKey:@"YourKey"];

and get data from another view using NSUserDefaults like this :

NSMutableArray *array=[[NSUserDefaults standardUserDefaults]objectForKey:@"YourKey"];

swift

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
      if segue.identifier == "toTabController" {
        var tabBarC : UITabBarController = segue.destinationViewController as UITabBarController
        var desView: CaseViewController = tabBarC.viewControllers?.first as CaseViewController

        var caseIndex = overviewTableView!.indexPathForSelectedRow()!.row
        var selectedCase = self.cases[caseIndex]

        desView.caseitem = selectedCase
      }
    }
Jay Bhalani
  • 4,142
  • 8
  • 37
  • 50
  • 2
    ya i can switch tab by self.tabBarController!.selectedIndex = 2, but how can i pass data from first tab's controller view to 3rd's tab controller view ? Actually my 1st tab's controllerView has a button and after button click, i want to pass some data to the 3rd tab's controller view. but how ? – Nuibb Feb 11 '15 at 13:27
  • you can use " NSUserDefaults " to save deta. – Jay Bhalani Feb 11 '15 at 13:28
  • yaa this is a great solution, but is there any direct way without storing data globally in NSUserDefaults ? This value will be frequently changed, so it would be better if there is a way like segue. Actually i tried to access a variable (keyword) of 3rd controller from 1st controller like - var thirdViewController : ThirdViewController = ThirdViewController() and thirdViewController.keyword = "Nuibb", but keyword variable always get nil in 3rd view controller. – Nuibb Feb 11 '15 at 14:11
  • To pass information between viewcontrollers, you could use either singleton, delegate or notifications. For your cause It's better to use a singleton I reckon. – rcat24 Feb 11 '15 at 14:22
  • Actually I want like this in swift - SecondViewController *secondViewController = [[SecondViewController alloc] initWithNib:@"SecondViewController" bundle:nil]; secondViewController.myValue = 5; [self pushViewController:secondViewController animated:YES]; I followed the post - http://prateekvjoshi.com/2014/02/16/ios-app-passing-data-between-view-controllers/ but i'm strugling to convert this obj-c code to swift. Please help me out. – Nuibb Feb 11 '15 at 14:26
  • You can't do it when navigating through tabs. The way you have it in Obj-c could be done if you're pushing a VC or presenting it modally. If you want to have a property being changed throughout the app, it will have to be done with a singleton or NSNotification. – rcat24 Feb 11 '15 at 14:50
  • @Jay Bhalani Thanks for your swift code. But i can't use any segue because segue redirects me as navigation with back button like push or modal that hides my tab bar and needs to dismiss. It's not my requirement. I only want to switch tab programmatically upon button click and pass some data from 1st tab to 3rd. – Nuibb Feb 12 '15 at 08:21
  • 1
    @rcat24 I tried with singleton but have some issues as i described in my upper answer. Can you tell me what should i do to get the singleton object's value multiple time upon button click, not once ? – Nuibb Feb 12 '15 at 08:26
  • 1
    @Nuibb Replace the code you have in viewDidLoad to viewWillAppear. – rcat24 Feb 12 '15 at 08:55
2

Okay, i tried with creating a singleton object in viewController of first tab and then get that object's value from viewController of third tabBar. It works only for once when third tab's view controller instantiates for the 1st time. I never got that singleton object's value in third tab's view controller except the first time. What can i do now ? In my code - In first tab's controller, if i click a button tab will be switched to third tab. Below is my code portion -

In First tab's controller -

@IBAction func sendBtnListener(sender: AnyObject) {
        Singleton.sharedInstance.brandName = self.searchDisplayController!.searchBar.text
        self.tabBarController!.selectedIndex = 2
}

In Third tab's Controller -

 override func viewDidLoad() {
     super.viewDidLoad()

     //Nothing is printed out for this portion of code except the first time 
     if !Singleton.sharedInstance.brandName.isEmpty{
         println(Singleton.sharedInstance.brandName)

     }else{

         println("Empty")
     }
 }

In Singleton Object's class -

class Singleton {
    var name : String = ""
    class var sharedInstance : Singleton {
        struct Static {
            static let instance : Singleton = Singleton()
        }
        return Static.instance
    }

    var brandName : String {
        get{
            return self.name
        }

        set {
            self.name = newValue
        }
    }
} 

Edited :

Okay at last it's working. For others who just want like me, please replace all the code from viewDidLoad() to viewWillAppear() method in third tab's (destination tab) controller and it will work. Thanks.

Nuibb
  • 1,800
  • 2
  • 22
  • 36