skip to Main Content

I have a modally-presented ViewController that has a UITableView inside it. When the user clicks "Days", it shows this view controller (modally). Here’s my Storyboard:

enter image description here

enter image description here

What I want to do is, when I click one of the cells in the table view in the modal, I want to dismiss the modal, but also load new data in the root view controller.

How can I have access to the root view controller from a segued view controller?

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.dismiss(animated: true, completion: nil)
}

// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! DayView
    if let indexPath = tableView.indexPathForSelectedRow {
        destinationVC.day = days![indexPath.row]
    }
}

I want something like what I’ve written above, but while my modal does get dismissed, but what I want is for somehow the code in the prepare function to fire when a TableViewCell is clicked.

2

Answers


  1. A shorter and simpler method than protocol/delegate is to create a closure:

    For sending a String back, In First ViewController:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let viewControllerB = segue.destination as? ViewControllerB {
            viewControllerB.callback = { message in
                
                //Do what you want in here!
    
            }
        }
    }
    

    In ViewControllerB:

    
    var callback : ((String) -> Void)?
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        callback?("Your Data")
        self.dismiss(animated: true, completion: nil)
    }
    
    
    Login or Signup to reply.
  2. you are in the right path,you need to add two more functions 1. unwindsegue and one this is not destination its source so you need change to source from destination.

     // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC = segue.source as! DayView
        if let indexPath = tableView.indexPathForSelectedRow {
            destinationVC.day = days![indexPath.row]
        }
    }
    

    for Reference : How to Pass Data in an Unwind Segue

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search