Search code examples
swiftxcodeuinavigationcontrollersegue

How to pass data between two screens while both are elements in NavigationController in Swift?


I have a set of storyboards under the UINavigation Controller. One of these screens contains a table view and I need to send the data of the clicked row to the next screen. I am aware that doing so would require me to use segue. But then how do I get the Navigation Bar and the Navigation Button

For better understanding I have uploaded the screen shot of my first screen. Clicking on the detail button is going to send the challenge object to next screen. However, I am looking forward to having the same navigation bar on the top of the next scree. Any idea how can I accomplish such objective?

Currently if I press on details button, I'll get the details of that challenge in the terminal.

@IBAction func CAStartChallenge(_ sender: UIButton) {
           let tag = NSNumber(value: sender.tag) as! Int
           print("challenge name to be printed : \(challengeTableConent[tag].display()) ")
}

enter image description here


Solution

  • In your storyboard you want to drag a segue between the view controllers, like so:

    Storyboard segue dragging

    Use either Show or Push (deprecated) options for the segue. Give this segue an appropriate identifier, such as Details.

    Then in your button function you can add these:

    @IBAction func CAStartChallenge(_ sender: UIButton) {
        let tag = NSNumber(value: sender.tag) as! Int
        performSegue(withIdentifier: "Details", sender: challengeTableConent[tag])
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "Details",
            let destination = segue.destination as? DestinationViewController,
            let model = sender as? ChallengeTableContentType {
    
            // pass through model to destination view controller
            destination.model = model
        }
    }
    

    You can then configure the destination view controller using its specific model when it appears.