您的位置:首页 > 其它

一种可展开伸缩的tableView实现

2016-07-28 20:59 337 查看
:##简单实现了一个可展开收缩的tableview,可多级展开,一次收缩,类似于树形结构,可扩展性强。

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: