Reputation: 1942
Sorry for being a complete noob at all this, but I am having trouble using the indexPathForSelectedRow() within the didSelectRowAtIndexPath function within a Table View.
What I'm trying to do is to capture the textLabel.text value of a cell in my table into NSUserDefaults, then transition that into a finalView. In the finalView, a label's text will be updated based on the value retrieved from the TableView.
Here's the code in my tableView:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexpath = tableView.indexPathForSelectedRow() as NSIndexPath! //supposed to get the correct index, but doesn't
let cell = tableView.cellForRowAtIndexPath(indexpath) as UITableViewCell!
captureCellVals.setObject(cell.textLabel?.text, forKey: "restoname")
//code to transfer to final view:
let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("finalView") as FinalView
self.navigationController?.pushViewController(view2, animated: true)
}
And now here is the code in the finalView:
class FinalView: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let values = NSUserDefaults.standardUserDefaults()
let restName = values.objectForKey("restoname") as String
Restaurant.text = restName
}
@IBOutlet weak var Restaurant: UILabel!
}
The thing is, this actually works. It is indeed retrieving the textLabel.text value of a cell, transitioning it into the FinalView, and updating the Restaurant.text to display the retrieved name. The problem is that it retrieves the incorrect name from the table.
for example, if i click a row with restaurant name 'Cafe France', the Restaurant.text changes to 'Tonys Cafe' instead of the intended 'Cafe France'. I think it's the indexes, but could it be something else? Thanks very much for any help.
Upvotes: 0
Views: 908
Reputation: 236360
You don't need to use let index path = whatever. TableView's method didSelectRowAtIndexPath already has indexPath parameter.
Just change your line
let cell = tableView.cellForRowAtIndexPath(indexpath) as UITableViewCell!
to
let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!
and delete this line
let indexpath = tableView.indexPathForSelectedRow() as NSIndexPath!
Once again NSUserDefaults has a specific method for loading your stored string called stringForKey()
Restaurant.text = NSUserDefaults().stringForKey("restoname") ?? ""
Upvotes: 1