Expand/collapse section in UITableView in iOS

前端 未结 17 1080
野的像风
野的像风 2020-11-22 08:49

Could somebody tell me the way to perform UITableView expandable/collapsible animations in sections of UITableView as below?

<

17条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 09:27

    So, based on the 'button in header' solution, here is a clean and minimalist implementation:

    • you keep track of collapsed (or expanded) sections in a property
    • you tag the button with the section index
    • you set a selected state on that button to change the arrow direction (like △ and ▽)

    Here is the code:

    @interface MyTableViewController ()
    @property (nonatomic, strong) NSMutableIndexSet *collapsedSections;
    @end
    
    ...
    
    @implementation MyTableViewController
    
    - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (!self)
            return;
        self.collapsedSections = [NSMutableIndexSet indexSet];
        return self;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        // if section is collapsed
        if ([self.collapsedSections containsIndex:section])
            return 0;
    
        // if section is expanded
    #warning incomplete implementation
        return [super tableView:tableView numberOfRowsInSection:section];
    }
    
    - (IBAction)toggleSectionHeader:(UIView *)sender
    {
        UITableView *tableView = self.tableView;
        NSInteger section = sender.tag;
    
        MyTableViewHeaderFooterView *headerView = (MyTableViewHeaderFooterView *)[self tableView:tableView viewForHeaderInSection:section];
    
        if ([self.collapsedSections containsIndex:section])
        {
            // section is collapsed
            headerView.button.selected = YES;
            [self.collapsedSections removeIndex:section];
        }
        else
        {
            // section is expanded
            headerView.button.selected = NO;
            [self.collapsedSections addIndex:section];
        }
    
        [tableView beginUpdates];
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
        [tableView endUpdates];
    }
    
    @end
    

提交回复
热议问题