My ultimate goal is to go to another view controller while passing a variable.
here's my code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let name : String=arrDict[indexPath.row].valueForKey("name") as! String
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "SecondSegue" {
let viewController = segue.destinationViewController as! SecondViewController
viewController.passedVariable = name
}
}
as you can see, I am trying to pass the variable name
to the function prepareForSegue
. as i said, my ultimate goal is to pass a variable to another view controller and open that view.
right now, prepareForSegue can do that but i just need the variable passed. maybe there is a way to do that directly in func tableView
?
var name: String?
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
name = arrDict[indexPath.row].valueForKey("name") as? String
performSegueWithIdentifier("SecondSegue", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if let viewController = segue.destinationViewController as? SecondViewController {
if name != nil {
viewController.passedVariable = name!
} else {
print("failed to get name from dictionary")
}
}
}
I believe this is what you are looking for. Do not assign the variable name in cellForRowAtIndexPath, because this function is normally called many times throughout the tableViews lifespan. Also, "name" needs to be a class variable so that you can assign it in one function and pass it in another. cellForRowAtIndexPath is a function for assigning the values and UI of each individual cell of the tableView. There are very few times to do anything else with it.