views:

1546

answers:

2

Hi, colud somebody tell me the way to do UITableView expandable/collapsable sections in UITableView as below?

http://cdn.mashable.com/wp-content/uploads/2009/07/beejive1.jpg or http:\\2aday.files.wordpress.com\2007\07\iphone1.png (sorry, cannot post more then one hlynk)

+3  A: 

I'm pretty sure you'll have to just make your own custom header row and just put that as the first row of each section. Subclassing the UITableView or the headers that are on there now would probably be a huge pain and I'm not sure you can easily get actions out of them the way they work now. You could easily set up a cell to LOOK like a header, and setup the tableView:didSelectRowAtIndexPath to expand or collapse the section it is within manually.

If I were you I'd store an array of booleans corresponding the the "expended" value of each of your sections. You could then have the tableView:didSelectRowAtIndexPath on each of your custom header rows toggle this value and then reload that specific section.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 if (indexPath.row == 0) {
  ///it's the first row of any section so it would be your custom section header

  ///put in your code to toggle your boolean value here
  mybooleans[indexPath.section] = !mybooleans[indexPath.section];

  ///reload this section
  [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
 }
}

You'd then setup your number numberOfRowsInSection to check the mybooleans value and return either 1 if the section isn't expanded, or 1+ the number of items in the section if it is expanded.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

 if (mybooleans[section]) {
  ///we want the number of people plus the header cell
  return [self numberOfPeopleInGroup:section] + 1;
 } else {
  ///we just want the header cell
  return 1;
 }
}

You would also have to update your cellForRowAtIndexPath to return a custom header cell for the first row in any section.

mjdth
you have done a fantabulous job .
hib
A: 

I have a better solution that you should add a UIButton into section header and set this button's size equal to section size, but make it hidden by clear background color, after that you are easily to check which section is clicked to expand or collapse

Son Nguyen