How to get textLabel of selected row in swift?
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)")
}
}
Swift 4
To get the label of the selected row:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
To get the label of the deselected row:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
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)