Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get textLabel of selected row in swift?

So i am trying to get the value of the textLabel of the row I select. I tried printing it, but it didn't work. After some research I found out that this code worked, but only in Objective-C;

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath    *)indexPath     {         NSLog(@"did select  and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);]     } 

I could not find any solution for Swift. Printing the indexpath.row is possible though, but that is not what I need.

so what should I do? or what is the 'Swift-version' of this code?

like image 974
Jonathan Neeskens Avatar asked Oct 02 '14 10:10

Jonathan Neeskens


People also ask

How do I get indexPath from cell Swift?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

How do I get a cell in Didselectrowat?

Use the below function and pass the index path of the selected row so that the particular cell is reloaded again. Another solution: store the selected row index and do a reload of tableview. Then in cellForRowAtIndexPath check for the selected row and change the accessory view of the cell.


2 Answers

Try this:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {      let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example      let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell      print(currentCell.textLabel!.text) 
like image 82
derdida Avatar answered Nov 03 '22 17:11

derdida


If you're in a class inherited from UITableViewController, then this is the swift version:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {     let cell = self.tableView.cellForRowAtIndexPath(indexPath)     NSLog("did select and the text is \(cell?.textLabel?.text)") } 

Note that cell is an optional, so it must be unwrapped - and the same for textLabel. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell and textLabel are both not nil:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {     let cell = self.tableView.cellForRowAtIndexPath(indexPath)     let text = cell?.textLabel?.text     if let text = text {         NSLog("did select and the text is \(text)")     } } 
like image 33
Antonio Avatar answered Nov 03 '22 19:11

Antonio