0

I am beginner in Swift and probably this is fundamental stuff but I need to get the index of the row (cell) I clicked on in the tableview.

I have TableViewController with predefined methods, but I wasn't able to find what I am looking for.

Rows (cells) are string from the string array.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Michal Moravik
  • 1,213
  • 1
  • 12
  • 23
  • Please review the documentation for UITableViewDelegate. – rmaddy Feb 21 '19 at 21:13
  • Or look at the several duplicates on this very site.Prefer documentation though. – keji Feb 21 '19 at 21:23
  • 2
    If you have a solution, do post it as an answer. Do not add it to your question. See [Ask questions, get answers, no distractions](https://stackoverflow.com/tour) – Bhargav Rao Feb 21 '19 at 21:44

3 Answers3

3

Implement table view delegate then you can detect your index cell by using method tableView(_:didSelectRowAt:): https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614877-tableview

Specifically:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("your row number: \(indexPath.row)")
}
qtngo
  • 1,594
  • 1
  • 11
  • 13
0
override func tableView(_ tableView: UITableView,
                        didSelectRowAt indexPath: IndexPath) {
    print(indexPath.row)
}
Michal Moravik
  • 1,213
  • 1
  • 12
  • 23
  • 2
    Instead of posting your own answer you should accept one of the other answers that told you how to do this. – rmaddy Feb 21 '19 at 22:49
  • 1
    @rmaddy you should be more observant. He edited his answer from the point "Specifically" after I posted my solution which I got from the comments where one guy told me to connect two things together. He is just hunting reputation and his goal was to be checked. Thank you. – Michal Moravik Feb 22 '19 at 02:23
-1

Your TableView contains TableViewCells. All the logic when you touch a cell can be programmed in

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

Update
indexPath.row will get you the index of the chosen tableviewcell

Ricardo
  • 26
  • 5