Search code examples
uitableviewcocoa-touchdidselectrowatindexpath

UITableViewDelegate didSelectRowAt Conditionally Execute based on Row


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?


Solution

  • 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
        }
    }
    

    App Image

    This would output: I'm row number 1 Recall that indexes start at zero.