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?
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.
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.
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)
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)") } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With