Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 900
D. Lin Avatar asked Mar 23 '16 09:03

D. Lin


People also ask

What is Prepareforsegue in Swift?

Notifies the view controller that a segue is about to be performed. iOS 5.0+ iPadOS 5.0+ Mac Catalyst 13.1+ tvOS 9.0+

How do you unwind segue in Swift?

In your storyboard, create an unwind segue by right-clicking a triggering object and dragging to the Exit control at the top of your view controller's scene.


1 Answers

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
            }
        }
    }
like image 165
Chirag D jinjuwadiya Avatar answered Oct 20 '22 22:10

Chirag D jinjuwadiya