Retrieve data from a cell using "willSelectRowAtIndexPath" in Swift2

I’ve been trying to get and output data from a TableView cell with many Tutorials since two weeks. But it seems that this cannot be done in Xcode. You can only get the selected cell in the cell, but I cannot read the text labels of the selected cell.

If the user selects a cell, I want to highlight the label value in the selected cell for the new view controller.

I can send the selected row only to the new view controller, but not to the label value in this selected cell.

func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { row = indexPath.row // here is the row the user has selcted labelStringOfselectedCell = "??????" // how to retrieve data from a label in the cell? return indexPath } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let DestViewController : ViewControllerDetail = segue.destinationViewController as! ViewControllerDetail DestViewController.seguedData = labelStringOfselectedCell } 
+4
source share
1 answer

If you really wanted to do something like this, you can do something like:

 func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { let cell = tableView.cellForRowAtIndexPath(indexPath) // do not confuse this with the similarly named `tableView:cellForRowAtIndexPath:` method that you've implemented let string = cell?.textLabel?.text return indexPath } 

Clearly, this depends on whether you are a custom cell subclass and what the label was, but this illustrates the basic idea.

Having said that , you should not do this. Your application must follow Model-View-Controller (MVC). When determining what data needs to be transferred to the next scene, you should return to the original model that you used when you initially populated the table, without referring to any control in the table.

For example, suppose you populate the original cell by extracting data from the objects model:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] cell.textLabel?.text = object.name return cell } 

Then you just implement prepareForSegue , which also retrieves data from objects (and you don’t need to implement willSelectRowAtIndexPath ):

 func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let destination = segue.destinationViewController as? ViewControllerDetail { let object = objects[tableView.indexPathForSelectedRow!.row] destination.seguedData = object.name } } 

Clearly, this will change depending on your model and how you originally populated the cell, but hopefully it illustrates the basic idea.

+2
source

All Articles