一种可展开伸缩的tableView实现
2016-07-28 20:59
337 查看
:##简单实现了一个可展开收缩的tableview,可多级展开,一次收缩,类似于树形结构,可扩展性强。
2、点击cell的时候先判断当前cell是展开还是未展开的
a、当前cell是未展开的,则以当前cell为父结点,查找其子结点,插入表中
b、当前cell已经展开,则从当前cell的下一行开始,到第一个深度不小于当前cell的位置为止,将此范围内的cell其数据删除。
2、didSelectRowAtIndexPath方法
demo地址:https://github.com/djcxym/YMTreeTableViewDemo
效果:
实现原理:
1、定义一个结构体作为Model,包含tableview将要展示的数据,还必须包含两个字段,一个是能标示其父结点的字段(名字,ID等),一个是结点深度字段2、点击cell的时候先判断当前cell是展开还是未展开的
a、当前cell是未展开的,则以当前cell为父结点,查找其子结点,插入表中
b、当前cell已经展开,则从当前cell的下一行开始,到第一个深度不小于当前cell的位置为止,将此范围内的cell其数据删除。
下面是具体实现,可根据需求自行扩展
1、结点类型@interface YMTreeNode : NSObject @property (nonatomic,copy) NSString *nodeName;//结点名字 @property (nonatomic,copy) NSString *parentNode;//父结点名字 @property (nonatomic,assign) NSInteger nodeDepth;//结点深度 @property (nonatomic,assign) BOOL expanded;//是否展开标志 - (instancetype)initWithName:(NSString*)name parent:(NSString*)parent depth:(NSInteger)depth expanded:(BOOL)expanded; @end
2、didSelectRowAtIndexPath方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { YMTreeNode *node = _data[indexPath.row]; if (node.expanded) {//已展开,则收回 NSInteger startPosition = indexPath.row+1; NSInteger endPosition = startPosition; for (NSInteger i=startPosition; i<_data.count; i++) { YMTreeNode *subNode = _data[i]; if (subNode.nodeDepth<=node.nodeDepth) { endPosition = i; break; } endPosition++; } if (endPosition == startPosition) { [self alert]; } else { [_data removeObjectsInRange:NSMakeRange(startPosition, endPosition - startPosition)]; NSMutableArray *indexPaths = [NSMutableArray array]; for (NSUInteger i=startPosition; i<endPosition; i++) { NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:i inSection:0]; [indexPaths addObject:tempIndexPath]; } [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone]; } } else {//未展开,则展开 NSArray *dataInsert = [self queryDataWithParent:node.nodeName andDepth:node.nodeDepth + 1]; if (dataInsert.count == 0) { [self alert]; } else { NSMutableArray *indexPaths = [NSMutableArray array]; for (NSInteger i = 0; i<dataInsert.count; i++) { YMTreeNode *node = dataInsert[i]; [self.data insertObject:node atIndex:indexPath.row + i + 1]; [indexPaths addObject:[NSIndexPath indexPathForRow:indexPath.row + i + 1 inSection:0]]; } [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; // [self.tableView reloadData]; } } node.expanded = !node.expanded; }
相关文章推荐
- 2016.07.28自学笔记----Android手机地图,开发只要5分钟?
- 生活、工作点滴(一)
- Oil Deposits hd 1241
- Java 理论与实践: 流行的原子
- 什么是SCRUM?
- 什么是SCRUM?
- Avoid The Lakes(DFS)
- spark error
- 超强PCB布线设计经验谈附原理图
- 银河英雄传说(codevs 1540)
- JS+DIV 实现拖动效果
- JavaScript清空、重置form表单
- POJ 3170--双重BFS
- 安卓手把手教你实现集成支付宝支付功能
- 拦截api
- linux 文件系统详解
- 二维码
- 变形课 hd 1181
- 真机Win7 64位,虚拟机MAC OS X 10.11用NAT无法上网问题,ip 169.254.xxx.xxx
- 纯命令提交代码到git仓库(教你怎么装逼)