Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect cell selection in UITableView in Swift?

How can I implement didSelectRowAtIndexPath: or something similar in my Swift app?

I have a populated Table View with several dynamic cells and I want to change views once a certain cell is selected.

I am able to get my head around it in Objective-C, but there is nothing on google to help me with Swift!

like image 217
Alex Avatar asked Feb 10 '15 11:02

Alex


People also ask

How do you get the IndexPath row when a button in a cell is tapped?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.


2 Answers

You can use didSelectRowAtIndexPath in Swift:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    NSLog("You selected cell number: \(indexPath.row)!")
    self.performSegueWithIdentifier("yourIdentifier", sender: self)
}

Just make sure you implement the UITableViewDelegate.

like image 75
Christian Avatar answered Oct 08 '22 04:10

Christian


This is how I managed to segue from UITableView cells to other view controllers after implementing cellForRow, numberOfRowsInSection & numberOfSectionsInTable.

//to grab a row, update your did select row at index path method to:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    NSLog("You selected cell number: \(indexPath.row)!");

    if indexPath.row == 1 {
        //THE SEGUE 
        self.performSegue(withIdentifier: "goToMainUI", sender: self)
    }
}

Will output: You selected cell number: \(indexPath.row)!

Remember to match the identifier of your segue in story board to the identifier in the function, e.g goToMainUI.

like image 42
WHC Avatar answered Oct 08 '22 03:10

WHC