rocket101
rocket101

Reputation: 7537

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

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 clarify:

  1. A user selects the cell with the label "foo"
  2. The code should return "foo", or whatever is selected by the user

Upvotes: 1

Views: 9379

Answers (2)

tiritea
tiritea

Reputation: 1279

Assuming you have the indexPath of the cell in question - eg from within any of your UITableViewDelegate or UITableViewDataSource methods,

BOOL selected = [tableView.indexPathsForSelectedRows containsObject:indexPath];

Upvotes: 7

bllakjakk
bllakjakk

Reputation: 5065

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])")
}

Upvotes: 3

Related Questions