我有一个类似的问题,这是我的解决方案。基本上,解决方案涉及更改单元格高度以“隐藏”它们。
我已将部分标题更改为自定义 UIControl,使其看起来像任何其他单元格,并实现了以下方法来“隐藏”所选部分之外的行:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == _selectedSection) {
// If it is the selected section then the cells are "open"
return 60.0;
} else {
// If is not the selected section then "close" the cells
return 0.0;
}
}
对于自定义标头,我使用了以下代码:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
CGFloat height = [self tableView:tableView heightForHeaderInSection:section];
// Here you can use whatever you want
CGFloat width = 640.0;
UIControl *view = [[UIControl alloc] initWithFrame:CGRectMake(0.0, 0.0, width, height)];
view.tag = section;
// This code is used by my custom UIControl
//
// to change the style for each state
// view.sectionSelected = (section == _selectedSection);
//
// and to change the title
// view.title = [self tableView:tableView titleForHeaderInSection:section];
// This event is used to "close" or "open" the sections
[view addTarget:self action:@selector(didSelectSectionHeader:) forControlEvents:UIControlEventTouchUpInside];
return view;
}
为了更吸引人,我在以下方法中添加了动画:
- (void)didSelectSectionHeader:(id)sender
{
if ([sender isKindOfClass:[UIControl class]]) {
// Save the old section index
int oldSelection = _selectedSection;
// Get the new section index
int tag = ((UIControl *)sender).tag;
// Get sections quantity
int numSections = [self numberOfSectionsInTableView:_tableView];
// Check if the user is closing the selected section
if (tag == _selectedSection) {
_selectedSection = -1;
} else {
_selectedSection = tag;
}
// Begin animations
[_tableView beginUpdates];
// Open the new selected section
if (_selectedSection >= 0 && _selectedSection < numSections) {
[_tableView reloadSections:[NSIndexSet indexSetWithIndex:_selectedSection] withRowAnimation:UITableViewRowAnimationAutomatic];
}
// Close the old selected section
if (oldSelection >= 0 && oldSelection < numSections) {
[_tableView reloadSections:[NSIndexSet indexSetWithIndex:oldSelection] withRowAnimation:UITableViewRowAnimationAutomatic];
}
[_tableView endUpdates];
}
}