Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an action when an user clicks on a cell in swift

I'm creating an app using Swift. I have an UITableView that I populate with some data from a database. When user clicks on a cell, I would like to trigger an action.

What I have done :

var array: [String] = ["example"]


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }



    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell(style :UITableViewCellStyle.Default, reuseIdentifier: "cell")
        cell.textLabel.text = array[indexPath.row]
        cell.tag = indexPath.row
        cell.targetForAction("getAction:", withSender: self)
        return cell
    }

    func getAction(sender:UITableViewCell)->Void {
        if(sender.tag == 0) {
            println("it worked")
        }
    }

I tried to adapt a solution from an another post but I did it definitely wrong. Thank you in advance

like image 940
soling Avatar asked Oct 30 '14 12:10

soling


2 Answers

Implement UITableViewDelegate and use didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

you can use the indexPath to get the item from your collection and perform your action

like image 63
Rajeev Bhatia Avatar answered Oct 28 '22 02:10

Rajeev Bhatia


In Swift 4, I believe the method has changed ever so slightly:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // your code
}
like image 25
Luan Nico Avatar answered Oct 28 '22 04:10

Luan Nico