Search code examples
swiftuitableviewuikituistoryboard

How can I send data through a UIButton from a DetailViewController to a TableViewController?


I'm creating a movie app in Swift using Storyboard, where you can search movies and add them to your movie collection. I have a table view controller where you can search movies, and a detail view controller when clicking on movies in that table view. I would like to be able to send data, after searching for a movie, from a ViewController to a different table view controller, which is the user's collection of movies.

I am doing this with an "Add Movie" button, but I'm not sure how to actually add these elements to my other table view controller. How can I send this data and add elements to my table view with this method? I believe I need a segue or delegate but I'm not quite sure how this would look in practice since I'm a newcomer to Swift and because of the added complexity of only adding elements to the table view when the button is clicked. Any help would be greatly appreciated.


Solution

  • You can pass data from view controllers like so:

    1: Define a segue programmatically in your table view controller.

        if let vc = storyboard?.instantiateViewController(identifier: "insert your view controller identifier") as? DetailViewController {
            navigationController?.pushViewController(vc, animated: true)
                   //vc.yourVariable = data
            }
        }
    
    

    2: Write a variable on your detailViewController

    var yourVariable = ""
    

    3: Inside your segue, add:

    vc.yourVariable = data
    

    What this does is whenever you call your transition function, you can set a variable in a different view controller to whatever movie the user choose.

    If you want to add this movie to a list, create an array and then append the movie the user choose to this array.

    It also sounds like you need to have some way for the data to persist. I recommend looking into CoreData so the array in which you store all this data will continue from session to session.

    To add data to a tableView, you need to edit the data in which the tableView is displaying (such as an array) and then call the tableView.reloadData() function for the new data to appear in the tableView.