rocket101 rocket101 - 5 months ago 12
Swift Question

How can I know if a cell of UITableView is selected?

Helo,

I am writing an app in Swift with XCode. It includes a UITableView. Just one question - in Swift, how can I tell what cell is selected by the user.

To clairify:


  1. A user selects the cell with the label "foo"

  2. What is some code that will retuen "foo", or whatever is selected by the user?



Thanks!

Answer

You can tell what cell is selected by User by adding following function in your view controller.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")
}

...

}

So now it depends that whether you are having an array to display the text names of each cell. If yes you can use this indexPath.row to retrieve the text of the row user selected.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var tableView : UITableView!
    var data:String[] = ["Cell 1","Cell 2","Cell 3","Cell 4"]


func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        let cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
        cell.text = self.data[indexPath.row]
        return cell
    }

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
         println("SELECTED INDEX /(indexPath.row)")
         println("Selected Cell Text /(data[indexPath.row])")
}