iOS中Cell的展開和收起
首先,先上圖,讓大家看看效果

Simulator Screen Shot 2017年5月22日 下午1.43.37.png
相信大家對於TableViewd資料的設定都熟悉,這方面就不多說的,重點的還是來看:
1.如何實現cell的展開和收起的效果
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.tableView deselectRowAtIndexPath:indexPath animated:NO]; currentRow = indexPath.row; NSDictionary *sectionDic = self.dataSource[indexPath.section]; NSArray *cellArray = sectionDic[@"sub"]; //cell當前的資料 NSDictionary *cellData = cellArray[indexPath.row]; NSString *key = [NSString stringWithFormat:@"%@", cellData[@"chapterID"]]; CellModel *chapterModel = [self.cellOpen valueForKey:key]; chapterModel.isShow = !chapterModel.isShow; [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; }
當用戶點選到某一個cell時候,需要判斷cell是否是展開狀態,如果張開或者收起就呼叫
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
讓cell的section能夠重新載入重新整理;
2.如何增加cell的某一個Section的row
2.1設定好對用是否展開row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *sectionDic = self.dataSource[indexPath.section]; NSArray *cellArray = sectionDic[@"sub"]; //cell當前的資料 NSDictionary *cellData = cellArray[indexPath.row]; NSString *key = [NSString stringWithFormat:@"%@", cellData[@"chapterID"]]; CellModel *model = [self.cellOpen valueForKey:key]; if (model.isShow) { return (model.pois.count+1)*60; } else { return 60; } }
2.2 返回對應的section的row
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ BOOL sectionStates = [self.sectionOpen[section] boolValue]; if(sectionStates) { //資料決定顯示多少行cell NSDictionary *sectionDict = self.dataSource[section]; //section決定cell的資料 NSArray *cellArray = sectionDict[@"sub"]; return cellArray.count; } else { //section是收起的時候 return 0; } }
好了,說了那麼多,估計大家還是喜歡看demo,以下是demo的連結: ofollow,noindex">https://github.com/xiaojin1123/SectionOpenAndClose.git