Expandable tableView in iphone

36,070

Solution 1

Finally i get two very useful helping link below which describes exact what the requirement is here Expanding/Collapsing TableView Sections
Collapsable Table View for iOS

Really, good articles for such kind of expanding/collapsing tableview sections

Solution 2

Use Following code for expandable Cell into UITableView

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text=[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"name"];
    [cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"level"] intValue]];    
    return cell;
}

code for expanding & collapsing rows – TableView DidSelectRow Method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *d=[self.arForTable objectAtIndex:indexPath.row];
    if([d valueForKey:@"Objects"]) {
        NSArray *ar=[d valueForKey:@"Objects"];
        BOOL isAlreadyInserted=NO;
        for(NSDictionary *dInner in ar ){
            NSInteger index=[self.arForTable indexOfObjectIdenticalTo:dInner];
            isAlreadyInserted=(index>0 && index!=NSIntegerMax);
            if(isAlreadyInserted) break; 
        }
        if(isAlreadyInserted) {
            [self miniMizeThisRows:ar];
        } else {        
            NSUInteger count=indexPath.row+1;
            NSMutableArray *arCells=[NSMutableArray array];
            for(NSDictionary *dInner in ar ) {
                [arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
                [self.arForTable insertObject:dInner atIndex:count++];
            }
            [tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
        }
    }
}

A Method which will help to minimize & maximize/expand-collapse rows.

-(void)miniMizeThisRows:(NSArray*)ar{
    for(NSDictionary *dInner in ar ) {
        NSUInteger indexToRemove=[self.arForTable indexOfObjectIdenticalTo:dInner];        
        NSArray *arInner=[dInner valueForKey:@"Objects"];
        if(arInner && [arInner count]>0){
            [self miniMizeThisRows:arInner];
        }
        if([self.arForTable indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
            [self.arForTable removeObjectIdenticalTo:dInner];
            [self.tableView deleteRowsAtIndexPaths:
              [NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexToRemove inSection:0]]
                      withRowAnimation:UITableViewRowAnimationRight];
        }
    }
}

You can download the source code from my tutorial site.

Solution 3

If this helps: [Access uitableview's expandable and collapsable sections] https://github.com/OliverLetterer/UIExpandableTableView

Solution 4

I have a little bit of a different approach to expandable table views - one that aligns with how these kinds of table views are generally built.

There are headers and there are cells. Headers should be tappable, and then cells underneath the headers would show or hide. This can be achieved by adding a gesture recognizer to the header, and when tapped, you just remove all of the cells underneath that header (the section), and viceversa (add cells). Of course, you have to maintain state of which headers are "open" and which headers are "closed."

This is nice for a couple of reasons:

  1. The job of headers and cells are separated which makes code cleaner.
  2. This method flows nicely with how table views are built (headers and cells) and, therefore, there isn't much magic - the code is simply removing or adding cells, and should be compatible with later versions of iOS.

I made a very simple library to achieve this. As long as your table view is set up with UITableView section headers and cells, all you have to do is subclass the tableview and the header. Try it :)

Link: https://github.com/fuzz-productions/FZAccordionTableView

enter image description here

Solution 5

Try Using this code... May be this can help.. And Feel free to Edit the code according to your requirements...

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()

@end

@implementation ViewController
@synthesize myTable;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //myTable.backgroundColor=[UIColor clearColor];
   // self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    muArr= [[NSMutableArray alloc]initWithObjects:@"Vinay",@"Anmol",@"Jagriti", nil];
    ExpArr=[[NSMutableArray alloc]initWithObjects:@"Useeee",@"Thissss",@"Codeee", nil];
    otherExpand=100;
    checker=100;

}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return muArr.count;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(otherExpand==section)
    return ExpArr.count;

    return  0;

}

-(BOOL)tableView:(UITableView *)table canCollapse:(NSIndexPath *)indexPath
{

    return NO;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Identifier=@"Cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell==nil)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];

    }
    cell.textLabel.text=[ExpArr objectAtIndex:indexPath.row];
    cell.textLabel.backgroundColor=[UIColor clearColor];
    UIView *viewww=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    viewww.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    cell.backgroundView=viewww;

   // cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];
    [tableView setSeparatorColor:[UIColor purpleColor]];

    return cell;

}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView *view1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [view1.layer setCornerRadius:20];
    view1.layer.borderWidth=2;
    view1.layer.borderColor=[UIColor brownColor].CGColor;
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 295, 44)];
    label.backgroundColor=[UIColor clearColor];

    label.text=[muArr objectAtIndex:section];
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    btn.frame=CGRectMake(280, -5, 50, 50);
    btn.backgroundColor=[UIColor clearColor];
    btn.tag=section;

    view1.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    label.textColor=[UIColor blackColor];
    label.font=[UIFont fontWithName:@"American TypeWriter" size:18];
    //btn.backgroundColor=[UIColor blackColor];
    [view1 addSubview:btn];
    [view1 addSubview:label];

    [btn addTarget:self action:@selector(Btntap:) forControlEvents:UIControlEventTouchUpInside];

    return view1;
}


-(void)Btntap : (UIButton *)btn
{
    if(otherExpand!=100)
    {
        if (otherExpand==btn.tag)
        {
            NSMutableArray *tempArr2=[[NSMutableArray alloc]init];
            for(int j=0;j<ExpArr.count;j++)
            {
                NSIndexPath *indexx1=[NSIndexPath indexPathForRow:j inSection:otherExpand];
                [tempArr2 addObject:indexx1];
            }
            checker=0;
            otherExpand=100;
            [myTable deleteRowsAtIndexPaths:tempArr2 withRowAnimation:UITableViewRowAnimationAutomatic];
        }

        else
        {
            NSMutableArray *tempArr2=[[NSMutableArray alloc]init];
            for(int j=0;j<ExpArr.count;j++)
            {
                NSIndexPath *indexx1=[NSIndexPath indexPathForRow:j inSection:otherExpand];
                [tempArr2 addObject:indexx1];
            }
            checker=1;
            otherExpand=100;
            [myTable deleteRowsAtIndexPaths:tempArr2 withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }

    if(checker!=0)
    {
        otherExpand=btn.tag;
        //checker=
        NSMutableArray *tempArr=[[NSMutableArray alloc]init];
        for(int i=0;i<ExpArr.count;i++)
        {
            NSIndexPath *indexx=[NSIndexPath indexPathForRow:i inSection:btn.tag];
            [tempArr addObject:indexx];
        }
        [myTable insertRowsAtIndexPaths:tempArr withRowAnimation:UITableViewRowAnimationAutomatic];

        checker=1;
    }
    checker=100;
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

@end
Share:
36,070
Rahul Patel
Author by

Rahul Patel

Updated on July 09, 2022

Comments

  • Rahul Patel
    Rahul Patel almost 2 years

    enter image description here

    I want to make this type of expandable/collapsible table view. there are categories and subcategories as in picture. for example "health and beauty" is a category and when i click this cell than its open subcategories as in picture below. So how can I make this type of table view? please suggest me.

  • Rahul Patel
    Rahul Patel over 10 years
    I tried it but not getting same thing as i want because my dictionary is dynamic
  • Luai Kalkatawi
    Luai Kalkatawi over 9 years
    @VinayKumar I have copy paste the code but it is not expanding could you help me with the code?
  • Uma Madhavi
    Uma Madhavi about 8 years
    @Vinay Kumar.. If i want to add different rows in each section means how can i modify . Suppose if section1=4,section2=6.
  • Vinay Kumar
    Vinay Kumar about 8 years
    @UmaMadhavi This is one of the codes that I used very long time ago. The better way to create Expand-Collapse Cells with sections is to Place a button in the Section Header. And when that button is pressed you have to insert the rows(with animation) in that particular section.
  • Uma Madhavi
    Uma Madhavi about 7 years
    @VinayKumar.. After long time i have to work with expand tableview. I want to expand section or row. How can i achieve this could u please guide me.
  • Vinay Kumar
    Vinay Kumar about 7 years
    What do you want to achieve exactly?
  • Aman Aggarwal
    Aman Aggarwal about 7 years
    One more link written using swift3 iostutorialjunction.com/2017/03/…
  • Okhan Okbay
    Okhan Okbay almost 7 years
    There is now a Swift version of this expandable table view library here -> ExpyTableView . It does not have downloadDataForSection and UIExpansionState notifier but all the other functionality are written in Swift and exists in new library.
  • iFateh
    iFateh over 2 years
    how to use DidSelectRow at Index method ?