Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I show/hide a certain cell in an UITableView depending on the state of another cell?

I have a UITableView with style "Grouped" which I use to set some options in my App. I'd like for one of the cells of this UITableView to only show up depending on whether another of this UITableView's cells is activated or not. If it's not, the first cell should show up (preferably with a smooth animation), if it is, the first cell should hide.

I tried returning nil in the appropriate -tableView:cellForRowAtIndexPath: to hide the cell, but that doesn't work and instead throws an exception.

I'm currently stuck and out of ideas how to solve this, so I hope some of you can point me in the right direction.

like image 308
Marco Peluso Avatar asked Jan 15 '10 13:01

Marco Peluso


3 Answers

You should remove the data behind the hidden cells from the table view's data source.

For example, if you are using an array, when an action occurs that causes a cell to be hidden, you would remove the object for that row from the array. Then, as the table view's data source, the array will return one less total count and only return valid cells for every row in that count (no nil).

This approach may require maintaining a second array with all of the objects (including hidden).

To update the view, check out reloadRowsAtIndexPaths:withRowAnimation:.

like image 105
gerry3 Avatar answered Nov 12 '22 21:11

gerry3


Here's a handy post in which the author provides some source code for performing animations on the currently selected cell:

http://iphonedevelopment.blogspot.com/2010/01/navigation-based-core-data-application.html

He's using this in a NSFetchedResultsController context, but you can see how he's using various calls to add/remove cells & sections.

Now, in your case, you'll need to modify whatever array you're using to host the data used to generate the rows in your tableView when you "activate" your cell, then selectively use:

  • tableView:insertRowsAtIndexPaths:withRowAnimation:
  • tableView:deleteRowsAtIndexPaths:withRowAnimation:
  • tableView:insertSections:withRowAnimation:
  • tableView:deleteSections:withRowAnimation:

to adjust things accordingly (you can start with tableView:reloadData:, but it's inefficient).

I realize that the API can be a bit daunting, but take the time to read through it and understand what the various calls do. Understanding how the UITableView uses its datasource and delegate, as well as the chain of events that occur when cells are selected/deleted/etc., is important if you want to get things just right (and crash-free).

like image 34
David Carney Avatar answered Nov 12 '22 21:11

David Carney


[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:withRowAnimation:]; // or insertRowsAtIndexPaths:withAnimation:
[tableView endUpdates]; 
like image 21
vaddieg Avatar answered Nov 12 '22 20:11

vaddieg