D. Lin
D. Lin

Reputation: 73

How do I use prepareForSegue in swift?

I have a ViewController with tableview called BasicPhrasesVC and I want to pass the data in the selected cell to display it on the next ViewController (called BasicPhrasesVC).

class BasicPhrasesVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

let basicPhrases = ["Hello.","Goodbye.","Yes.","No.","I don't understand.","Please?","Thank you.","I don't know."]
var selectedBasicPhrase = ""

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return basicPhrases.count
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
    cell.textLabel?.text = basicPhrases[indexPath.row]
    return cell
}

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

I am unsure of what to put here (I want to pass on the variable "selectedBasicPhrase")

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    selectedBasicPhrase = basicPhrases[indexPath.row]
    performSegueWithIdentifier("BasicPhrasesVC2BasicDisplayVC", sender: self)

}
}

Any help is appreciated.

Upvotes: 5

Views: 11206

Answers (3)

Chirag D jinjuwadiya
Chirag D jinjuwadiya

Reputation: 643

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    selectedBasicPhrase = basicPhrases[indexPath.row]
    self.performSegueWithIdentifier("BasicPhrasesVC2BasicDisplayVC", sender: selectedBasicPhrase)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "BasicPhrasesVC2BasicDisplayVC" {
            if let nextVC = segue.destinationViewController as? NextViewController {
                nextVC.selectedBasicPhrase = sender
            }
        }
    }

Upvotes: 9

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

Check segue name than take destinationViewController and send you're data to it.

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "BasicPhrasesVC2BasicDisplayVC") {
        let viewController:ViewController = segue!.destinationViewController as ViewController
        viewController.selectedBasicPhrase = "Test phrase"
    }
}

Upvotes: 0

Ujjwal Khatri
Ujjwal Khatri

Reputation: 836

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "<segue name>") {
        // pass the data
    }
}

Upvotes: 0

Related Questions