效果圖 :
cell的刪除與插入.gif
數據來源 :
plist1.png
plist2.png
主要代碼 解析:
1.點擊每組的代理 -- 控制器中實現
pragma mark - ExpandHeaderFooterViewDelegate
- (void)didSelectedHeaderFooterView: (ExpandHeaderFooterView *)headerFooterView {
// 1.關閉展開的組
if (self.isOpen && self.lastSelectedSection != headerFooterView.tag) {
self.isOpen = NO;
// 先收起之前組的箭頭
ExpandHeaderFooterView *view = (ExpandHeaderFooterView *)[self.tableView headerViewForSection:self.lastSelectedSection];
[view changeArrowWithIsOpen:NO];
// 刪除所展開的cell
NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:0 inSection:self.lastSelectedSection];
[self.tableView deleteRowsAtIndexPaths:@[deleteIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
// 2.點擊同一組處理
if (self.isOpen && self.lastSelectedSection == headerFooterView.tag) {
self.isOpen = NO;
// 刪除所展開的cell
NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:0 inSection:self.lastSelectedSection];
[self.tableView deleteRowsAtIndexPaths:@[deleteIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
return ;
}
// 3.展開所點擊的組(非同一組)
self.isOpen = YES;
self.lastSelectedSection = headerFooterView.tag;
NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:0 inSection:headerFooterView.tag];
[self.tableView insertRowsAtIndexPaths:@[insertIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
2.模型中的代碼 :
---.h文件
@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) NSArray *texts;
/// 自定義屬性
/// 存放每個組中文本的計算高度, 用于在cell中創建label時設置高度
@property (nonatomic, strong, readonly) NSArray *everyTextHeightArray;
/// 每個cell的最終高度
@property (nonatomic, assign) CGFloat cellHeight;
@end
---.m文件
- (NSArray *)everyTextHeightArray {
NSMutableArray *tmpMarray = [NSMutableArray array];
_cellHeight = 0;
for (int i = 0; i<_texts.count; i++) {
NSString *text = _texts[i];
CGFloat textHeight = [text boundingRectWithSize:CGSizeMake(APP_SCREEN_WIDTH - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height + 15; // 加15: 每個label之間的距離
_cellHeight += textHeight;
[tmpMarray addObject:@(textHeight)];
}
return tmpMarray;
}