vinnitu vinnitu - 1 year ago 593
iOS Question

Expand/collapse section in UITableView in iOS

Could somebody tell me the way to perform

expandable/collapsible animations in
as below?



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.