Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView tap to deselect cell

I have a UITableViewCell that is selected when tapped. During this selected state, if the user taps the cell again, I want the cell to deselect.

I can't find any of the delegate calls being hit. Any ideas how to implement this? Is it really going to be a gesture recognizer?

like image 982
Paul de Lange Avatar asked Oct 02 '12 15:10

Paul de Lange


People also ask

What is deselectRow?

deselectRow(at:animated:)Deselects a row that an index path identifies, with an option to animate the deselection.

What is Table View delegate?

func tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath) Tells the delegate the table view is about to draw a cell for a particular row. func tableView(UITableView, indentationLevelForRowAt: IndexPath) -> Int. Asks the delegate to return the level of indentation for a row in a given section.


2 Answers

You can actually do this using the delegate method willSelectRowAtIndexPath:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {     UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];     if ([cell isSelected]) {         // Deselect manually.         [tableView.delegate tableView:tableView willDeselectRowAtIndexPath:indexPath];         [tableView deselectRowAtIndexPath:indexPath animated:YES];         [tableView.delegate tableView:tableView didDeselectRowAtIndexPath:indexPath];          return nil;     }      return indexPath; } 

Note that deselectRowAtIndexPath: won't call the delegate methods automatically, so you need to make those calls manually.

like image 177
prisonerjohn Avatar answered Oct 05 '22 07:10

prisonerjohn


in Swift 4:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {      if let indexPathForSelectedRow = tableView.indexPathForSelectedRow,         indexPathForSelectedRow == indexPath {         tableView.deselectRow(at: indexPath, animated: false)         return nil     }     return indexPath } 
like image 41
Matias Elorriaga Avatar answered Oct 05 '22 07:10

Matias Elorriaga