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
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
In Swift 4, I believe the method has changed ever so slightly:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// your code
}
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