简体   繁体   中英

Pass Data to Detail View by Tapping TableView Cell

I'm trying to make a communication between tableview and it's detail view

Please can you check my way and give me some advices

So, I embedded Navigation Controller to Table view

and I didn't use tableview(_:didSelectedRowAt) method.

Some answers in Stackoverflow, they said override prepare(:) method and write the performSegue(withIdentifier:) method in the tableview(_:didSelectedRowAt)

but if i write the code like above two screens were shown.

(I think because segue action are triggered twice)

I just drag and drop the segue action(push) to Detail View from table view cell (Friends Name Cell)

By using this segue action, i can pass the data by prepare(:segue) method for editing selected friend name at the Detail View

and if i edit friend name from detail view's text field, there is edit button which trigger the unwind segue

so I override prepare(:segue) method in Detail View Controller

and wrote code below at Table View's ViewController

@IBAction func getEditedNameFromDetailView(_ sender:UIStoryboardSegue){
    if sender.source is DetailViewController {
        if let senderVC = sender.source as? DetailViewController {
            data[(self.someTableView.indexPathForSelectedRow?.row)!] = senderVC.editedData!
        }
        someTableView.reloadData()
    }
}

is this a proper way to communicate table view and its detail view?

From your description it is possible that you have 2 segues. one in the StoryBoard and one in your code.

The prepare method is not performing the segue. it simply gives you a chance to perform actions that are related to the segue, for example pass data to the destinations controller. do not call perform segue if you already created one in the StoryBoard and vice versa.

a common usage of prepare will look like this:

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //get the destination controller and cast it to your detail class
        if let destinationController  = segue.destination as? YourDetailClassHere {
           //set the properties you want
            destinationController.someProperty = someValue
        }
    }

Few notes -

  • you can use the sender object to pass data from the perform call.
  • common mistake is to assume that the destination controller is always your detail controller. it can be the navigation controller and then you will have to extract the detail from the navigation controller.

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