bbkrz bbkrz - 17 days ago 9
iOS Question

How to pass selected row string in table view to another ViewController page? (Swift 2)

I am running Xcode 7.3 and using Swift 2.2. I am having trouble passing data from my first view controller to the second view controller. I've created a variable

string
in my first view controller that holds the selected row in the tableview and it works. I have also created another variable
string
in my second view controller that should hold the name of the selected row, then pass the text to a label.

import UIKit
import Parse
import ParseUI

class FruitListPage: UIViewController, UITableViewDelegate, UITableViewDataSource {


var selectedFruit = String()

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

let fruitName:Scanner2 = self.storyboard?.instantiateViewControllerWithIdentifier("scanPage") as! Scanner2
fruitName.loadView()
let nameShop = textArray[indexPath.row]
print(nameShop)
selectedFruit = nameShop

print(selectedFruit)

fruitName.selectedFruit2 = selectedFruit

}


Everything works completely fine unit here in the first view controller and I can see the fruit name every time I press a row in the tableview. The real problem is that
selectedFruit2
string in the second view controller never grabs the data from the first view controller. Any clue?

import UIKit
import Parse

class Scanner2: UIViewController {

@IBOutlet var fruitNameLabel: UILabel!

var selectedFruit2 = String()

override func viewDidLoad() {
super.viewDidLoad()

print(selectedFruit2)

}

}

Answer

Connect your viewController in storyBoard with a segue and set its identifier as "scanPageSegue" for instance... then:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier("scanPageSegue", sender: textArray[indexPath.row])
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "scanPageSegue" {
        if let fruitName = segue.destinationViewController as? Scanner2, 
           selectedFruit = sender as? String {
            fruitName.selectedFruit2 = selectedFruit
        }
    }
}