I am interested in being able to conditionally execute code based on what row a user selects. Is there a way to associate an identifier with each row (cell) in cellForRowAt to help distinguish which row is selected to be used in DidSelectRowAt delegate?
Asked
Active
Viewed 1,089 times
1 Answers
1
Yes. You are correct in using the DidSelectRowAt
method. If you have a view controller with the table, the view controller will have to adopt the two standard delegates: UITableViewDataSource
, UITableViewDelegate
.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var table: UITableView!
let message:[String] = ["Hello", "World", "How", "Are", "You"]
/* Table with five rows */
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
/*Have a simple table with cells being the words in the message */
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = message[indexPath.row]
return cell
}
/*Optional method to determine which row was pressed*/
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
print("I'm row number "+String(indexPath.row))
}
/*set the table's delegate and datasource to the view controller*/
override func viewDidLoad() {
super.viewDidLoad()
self.table.delegate = self
self.table.dataSource = self
}
}
This would output:
I'm row number 1
Recall that indexes start at zero.

Miket25
- 1,895
- 3
- 15
- 29
-
I have this built out already - sorry for not posting what I currently have (its rather extensive). I'm wondering if there's a way to associate what is displayed on cellForRowAt, and then be able to be referenced in didSelectRowAt. For example, if I were to click on the row and it says "Hello", execute one thing, and if the row says "World", execute another. – Kevin Jan 07 '18 at 22:06
-
@Kevin A way to go about it is to simply use a switch statement to handle what `indexPath.row`is in the `DidSelectRowAt` method, and call the appropriate function that corresponds to that row. – Miket25 Jan 07 '18 at 22:09
-
what values are held in indexPath.row? From my understanding, I thought it only was the row number selected. Is there more information that is associated with indexPath.row? – Kevin Jan 07 '18 at 22:14
-
Yes, by using the row number to look up the appropriate entry in your data source. – jscs Jan 07 '18 at 22:17