简体   繁体   中英

Passing data with tabBar DidSelectItem using tags and PerformSegueWithIdentifier

I am using swift 3 have a taBbar and when I select an tabBarItem the segue is called programatically to go to a new View Controller. I also need to pass some data with this segue.

my code (for tabbar didSelectItem):

 func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        if item.tag == 0 {
            self.performSegueWithIdentifier("nearbyHotelsSegue", sender: nil)
        } else if item.tag == 1 {
            self.performSegueWithIdentifier( "nearbyRestaurantsSegue", sender: nil)
        } else if item.tag == 2 {
            self.performSegueWithIdentifier( "nearbyEventsSegue", sender: nil)
        } else if item.tag == 3 {
            self.performSegueWithIdentifier( "morePlacesSegue", sender: nil)
        } 
    }

From my research so far, I know that can use PrepareForSegue for this, but I can't use this inside the tabBar (didSelectItem) method. How can I pass data using tabbar didSelectitem method or is there any other good way to achieve this? Thanks.

The prepareForSegue method is used as an overridden one, so you should use it out of tabBar function's bounds. When you call performSegue(withIdentifier: "segueName", sender: nil) , you have given nil in sender. Sender is the parameter of type Any? , where you put your custom data you want to pass to another controller. In prepare(forSegue: UIStoryboardSegue, sender: Any?) when you cast your destination view controller as the one you want to use, pass the sender data to this controller, eg:

override func prepare(forSegue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? YourDestinationViewController {
controller.receivedData = sender
}
}

I solved this using the following code. it seems prepareForSegue is not effected by the use of PerformSegueWithIdentifier to perform the segue programmatically.
So I used the code posted in the question unchanged and then added the following code to pass data.

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "nearbyHotelsSegue" {

            if let toViewController = segue.destinationViewController as? NearbyHotelsViewController {
                toViewController.returnedText = (searchBaseItem?.baseItemId)!
            }
        }

//....other ifs
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM