Nishi
Nishi

Reputation: 703

Want to expand and collapse UITableview Section

I want to expand UITableView section where I have to show UITableViewCells. What should I do to achieve this?

Upvotes: 2

Views: 9368

Answers (2)

Ding
Ding

Reputation: 61

According to Vignesh's answer, I have tried the second solution."On touching the section header reload the table with updated rows count for section touched."

First, declare an array to store the isExpanded tag for each section.Initial, all value is BOOL NO.Means all the section rows are collapsed.

Then, in the

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

method, implement the sectionHeader touch event by following code: Because I use a custom cell as section header view. so here is the "cell",you can use your own view.

cell.tag=section;
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionTapped:)];

[cell addGestureRecognizer:recognizer];
cell.userInteractionEnabled=YES;

And, do something when the sectionHeader is tapped.

- (void)sectionTapped:(UITapGestureRecognizer *)recognizer
{

    NSMutableArray *isSectionTouched=[[NSMutableArray alloc]initWithCapacity:_sectionExpandBool.count];
    isSectionTouched=[_sectionExpandBool mutableCopy];
    if ([[isSectionTouched objectAtIndex:recognizer.view.tag]boolValue]==YES) {
        [isSectionTouched replaceObjectAtIndex:recognizer.view.tag withObject:[NSNumber numberWithBool:NO]];
    }else if ([[isSectionTouched objectAtIndex:recognizer.view.tag]boolValue]==NO){
        [isSectionTouched replaceObjectAtIndex:recognizer.view.tag withObject:[NSNumber numberWithBool:YES]];
    }
    _sectionExpandBool=isSectionTouched;
    [self.tableView reloadData];

 }

Don't forget to modify the numberOfRowsInSection method. The row.count should change according the value of _sectionExpandBool, if the section's ExpandBool is YES, should return the correct number of your datasource,else return 0.

It works as my expectation. However, I'm a little worried about the memory leak or something, because every time tap the header, the whole table view will reload again.

I wonder if there is some solution for only reload the specific section. Thanks.

Upvotes: 0

Vignesh
Vignesh

Reputation: 10251

  • A simple implementation would be keep your cell height as zero for sections.
  • Make the viewForSectionHeader touchable
  • When you touch it, set proper height for cells under the section
  • Write a logic for switching between sections

OR,

  • On touching the section header reload the table with updated rows count for section touched.

Many other ways to do it. Apple example.

Upvotes: 6

Related Questions