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

16,230

Solution 1

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).

Solution 2

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:.

Solution 3

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:withRowAnimation:]; // or insertRowsAtIndexPaths:withAnimation:
[tableView endUpdates]; 
Share:
16,230
GalSh8
Author by

GalSh8

Updated on June 05, 2022

Comments

  • GalSh8
    GalSh8 almost 2 years

    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.

  • GalSh8
    GalSh8 over 14 years
    Thanks, I figured it out with the help of your post! :)
  • GalSh8
    GalSh8 over 14 years
    Thank you, this was helpful as well. A soon as my reputation allows, I will upvote this.