How to expand and collapse rows using header section in a UITableView

25,129

Solution 1

I draft up some code to give you the idea. The concept is we keep track of collapsed section in NSMutableSet and add/remove it according to the user touch on the section. The collapse/expand animation is actually the animation of adding/removing cells.

#import "ViewController.h"

@interface ViewController () < UITableViewDataSource, UITableViewDelegate> {
    NSMutableSet* _collapsedSections;
}

@property (nonatomic, weak) IBOutlet UITableView* tableView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _collapsedSections = [NSMutableSet new];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_collapsedSections containsObject:@(section)] ? 0 : 10;
}

-(NSArray*) indexPathsForSection:(int)section withNumberOfRows:(int)numberOfRows {
    NSMutableArray* indexPaths = [NSMutableArray new];
    for (int i = 0; i < numberOfRows; i++) {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:section];
        [indexPaths addObject:indexPath];
    }
    return indexPaths;
}

-(void)sectionButtonTouchUpInside:(UIButton*)sender {
    sender.backgroundColor = [UIColor greenColor];
    [self.tableView beginUpdates];
    int section = sender.tag;
    bool shouldCollapse = ![_collapsedSections containsObject:@(section)];
    if (shouldCollapse) {
        int numOfRows = [self.tableView numberOfRowsInSection:section];
        NSArray* indexPaths = [self indexPathsForSection:section withNumberOfRows:numOfRows];
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
        [_collapsedSections addObject:@(section)];
    }
    else {
        int numOfRows = 10;
        NSArray* indexPaths = [self indexPathsForSection:section withNumberOfRows:numOfRows];
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
        [_collapsedSections removeObject:@(section)];
    }
    [self.tableView endUpdates];
    //[_tableView reloadData];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIButton* result = [UIButton buttonWithType:UIButtonTypeCustom];
    [result addTarget:self action:@selector(sectionButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    result.backgroundColor = [UIColor blueColor];
    [result setTitle:[NSString stringWithFormat:@"Section %d", section] forState:UIControlStateNormal];
    result.tag = section;
    return result;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* result =  [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    result.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row];
    return result;
}

@end

Solution 2

As already this is a old question now.Me too also searched and in the last got 1 sample code from Github.So I thought of sharing the link,if in near future any one comes up with the same issues. https://github.com/iSofTom/STCollapseTableView

Solution 3

TLIndexPathTools does this with only a few lines of code on your part. Try running the Collapse sample project. It subclasses TLCollapsibleTableViewController, which has a couple of nice options. It supports expanding a single section at a time or multiple sections. It also optimizes the scroll position when you expand a section to show as many rows of the section as possible. So if you tap on a section near the bottom of the screen, it will scroll up automatically.

The full view controller code of the sample project is as follows:

#import "TLCollapsibleTableViewController.h"

@interface CollapseTableViewController : TLCollapsibleTableViewController
- (IBAction)toggleSingleSectionExpanded:(UISwitch *)sender;
@end

#import "CollapseTableViewController.h"
#import "TLIndexPathSectionInfo.h"
#import "TLCollapsibleDataModel.h"

#define SECTION1_NAME @"Section 1"
#define SECTION2_NAME @"Section 2"

@interface CollapseTableViewController ()
@property (strong, nonatomic) TLIndexPathDataModel *backingDataModel;
@end

@implementation CollapseTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //define items for two sections
    NSArray *section1Items = @[
                               @"Fredricksburg",
                               @"George Washington",
                               @"Grand Canyon"];
    NSArray *section2Items = @[
                               @"Jelly Bean",
                               @"Bibliography",
                               @"Keyboard Shortcut",
                               @"Metadata",
                               @"Fundamental",
                               @"Cellar Door"];

    //We're using plain string items, so we don't have a sectionNameKeyPath property
    //to use, so instead we explicitly create section info objects
    TLIndexPathSectionInfo *section1 = [[TLIndexPathSectionInfo alloc] initWithItems:section1Items andName:SECTION1_NAME];
    TLIndexPathSectionInfo *section2 = [[TLIndexPathSectionInfo alloc] initWithItems:section2Items andName:SECTION2_NAME];

    //create the backing model, which contains all sections and items
    self.backingDataModel = [[TLIndexPathDataModel alloc] initWithSectionInfos:@[section1, section2]
                                                                           andIdentifierKeyPath:nil andCellIdentifierKeyPath:nil];

    [self collapseAll];
}

- (void)tableView:(UITableView *)tableView configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSString *item = [self.dataModel itemAtIndexPath:indexPath];
    cell.textLabel.text = item;
}

- (IBAction)toggleSingleSectionExpanded:(UISwitch *)sender {
    self.singleExpandedSection = sender.isOn;
    [self collapseAll];
}

- (void)collapseAll
{
    self.dataModel = [[TLCollapsibleDataModel alloc] initWithBackingDataModel:self.backingDataModel
                                                        collapsedSectionNames:[NSSet setWithArray:self.backingDataModel.sectionNames]];
}

@end
Share:
25,129
adevani11
Author by

adevani11

Updated on July 10, 2022

Comments

  • adevani11
    adevani11 almost 2 years

    I have a table view. Now I want to collapse and expand rows by tapping on the section header. In other words, when I tap the header the rows display for that section. How can I do this?