Send data from TableView to DetailView Swift

Here is the example for you:

var valueToPass:String!

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow!
    let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell

    valueToPass = currentCell.textLabel.text
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "yourSegueIdentifer") {
        // initialize new view controller and cast it as your view controller
        var viewController = segue.destinationViewController as AnotherViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass
    }
}

But don’t forget to create a passedValue variable into your DetailViewController.

This is just an example of passing data from one viewController to another and you can pass data with this example as you need.

And for more info refer this links.

Passing values between ViewControllers based on list selection in Swift

Use didSelectRowAtIndexPath or prepareForSegue method for UITableView?

Swift: Pass UITableViewCell label to new ViewController

https://teamtreehouse.com/forum/help-swift-segue-with-variables-is-not-working

May be this will help you.

Swift 3.0

var valueToPass:String!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow!
    let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell

    valueToPass = currentCell.textLabel?.text
    performSegue(withIdentifier: "yourSegueIdentifer", sender: self)
}

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "yourSegueIdentifer") {
        // initialize new view controller and cast it as your view controller
        var viewController = segue.destination as! AnotherViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass
    }
}

Leave a Comment