简单实现tableView折叠列表

来源:互联网 发布:淘宝企业店铺升级流程 编辑:程序博客网 时间:2024/05/21 12:50

折叠列表在以文字内容为主的网站上很常见,主要用于对导航连接进行分类,包含一个分段列表,每个分段下有一些子选项,可以展开各个子项,也可以关闭,现在来设计一个这样的列表,首先需要建一个View用来响应点击事件的(展开列表 关闭列表,在这个过程中表视图控制器会做两件事:1更新模型及更新数据  2更新表视图 可以把点击的分段保存下来,作为当前的展开索引 之后可以刷新列表 ,方法有两种:

1 reloadData ,之后调用insertRowsAtIndexPath:With  和 DeleteRowsAtindexPath:with方法

2 在beginUpdates 和endUpdates之间执行插入或删除,这里要注意更新数据的正确性,必须与表视图匹配,不然会发生崩溃,以下是部分关键代码:

-(void) openAccordionAtIndex:(int) index {
 
  NSMutableArray *indexPaths = [NSMutableArray array];
 
  int sectionCount = [[self.objects objectForKey:[[self.objects allKeys] objectAtIndex:self.currentlyExpandedIndex]] count];
 
  for(int i = 0; i < sectionCount; i ++) {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:self.currentlyExpandedIndex];
    [indexPaths addObject:indexPath];
  }
 
  self.currentlyExpandedIndex = -1;
 
  [self.tableView deleteRowsAtIndexPaths:indexPaths
                        withRowAnimation:UITableViewRowAnimationTop];
 
  self.currentlyExpandedIndex = index;
 
  sectionCount = [[self.objects objectForKey:[[self.objects allKeys] objectAtIndex:self.currentlyExpandedIndex]] count];
 
  [indexPaths removeAllObjects];
  for(int i = 0; i < sectionCount; i ++) {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:self.currentlyExpandedIndex];
    [indexPaths addObject:indexPath];
  }
 
  double delayInSeconds = 0.35;
  dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
  dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [self.tableView insertRowsAtIndexPaths:indexPaths
                          withRowAnimation:UITableViewRowAnimationFade];
  });
 
  [self.tableView endUpdates];
}

0 0
原创粉丝点击