Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform action when UITableViewCell is clicked

I am making an tvOS app for the Apple TV but I have some problems with my UITableView. When I click on a UITableViewCell nothing happens. I am using targetForAction but it doesn't seem to work.

This is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.dataSource = self
    self.tableView.delegate = self
}

let allData = ["Los Angeles","New York","San Fransisco"]

@IBOutlet weak var tableView: UITableView!

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)
    cell.textLabel?.text = "\(allData[indexPath.row])"
    cell.targetForAction("buttonClicked:", withSender: self)
    return cell
}

func buttonClicked(sender:AnyObject) {
    print("button clicked!")
}
like image 741
O.Olivier Avatar asked Dec 05 '25 00:12

O.Olivier


2 Answers

I found the solution. I had to add this function:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("selected cell \(indexPath.row)")
}
like image 79
O.Olivier Avatar answered Dec 07 '25 15:12

O.Olivier


Swift 5:

func tableView(_ tableView: UITableView, didSelectRowAtindexPath indexPath: IndexPath) {
    print(indexPath.row)
}
like image 45
ilkayaktas Avatar answered Dec 07 '25 17:12

ilkayaktas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!