Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift xCode 6.4 - using a variable generated by a tableview controller in a second view controller

I am am googling around the whole day for a probably simple question but I do not get it right. Hopefully someone can help me.

I have a tableview controller with one prototype cell containing three custom labels. When I run the app the table view controller will generate about 150 tableview cells with content parsed form a csv-file.

When I click on one of these cells the user will be forwarded two a second view controller showing some additional infotext for his cell selection. During the same time the user is clicking the tabelview cell a variable will be updated to the corresponding tableview-row-number (e.g. 150 for the last tableview cell. Now I want to use this variable as reference text within the text shown in the second view controller.

The variable in the tableview controller is "rowSelectedFromList" and will be set by the following code:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var rowSelectedFromList: String

    rowSelectedFromList = rowOfItems[indexPath.row].customlabel3!
    println(rowSelectedFromList)
}

The "println" is just for checking if it works correctly and it does.

The question is how can I use the variable "rowSelectedFromList" in the second view controller?

Appreciate your help, thanks!

like image 740
Olli D. Avatar asked Jun 27 '26 18:06

Olli D.


1 Answers

You can add your custom logic in prepareForSegue like this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let controller = segue.destinationViewController as? YourSecondController,
            indexPath = tableView.indexPathForSelectedRow() {
        controller.someVariable = rowOfItems[indexPath.row].customlabel3!
    }
}

Replace YourSecondController with class name for second view controller.

Don't forget to create IBOutlet for your UITableView and name it tableView.

like image 187
glyuck Avatar answered Jun 29 '26 08:06

glyuck