想要在TableView中实现动态添加某一个Cell被点击后,展开显示其他的UIView,简单的方式是可以在点击某个cell时,修改另外一个cell(重画另一个UIView的cell,默认高度未0,这样就显示不出来)修改高度,并且重载一下TableView,简单代码如下:
-(void)headViewClick:(UIButton*)sender {
NSIndexPath *tagPath = [NSIndexPath indexPathForItem:0 inSection:sender.tag];
NSNumber *object = [NSNumber numberWithInt:sender.tag];
BOOL onShow=NO;
if (![sectionHeaderHover containsObject:object]) {
// 需要展开的添加到数组中
[sectionHeaderHover addObject:object];
onShow = YES;
} else {
//已经在数组中得,说明已经展开,再次点击将它移除
[sectionHeaderHover removeObject:object];
}
// 注意这个一定要在调用 cellForRowAtIndexPath 前,否则cell画出会错乱,因为这个调用后,马上回对tagPath的Cell重画
//而在cellForRowAtIndexPath后调用,addsubview 会被更新掉
[self.contentTableView reloadRowsAtIndexPaths:@[tagPath] withRowAnimation:UITableViewRowAnimationAutomatic];
if (onShow) {
if (sectionHeaderHover == nil) {
sectionHeaderHover = [[NSMutableArray alloc]init];
}
// 获取 tag 对应的cell view,这里可以对view重新设置 在伸展后的view
UITableViewCell *cell = (id)[self.contentTableView cellForRowAtIndexPath:tagPath];
TagView *view = [[TagView alloc]initWithFrame:CGRectMake(0, 0, 320, 150)];
[view setData:sectionArray[sender.tag]];
[cell addSubview:view];
}
}
修改cell 高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.contentTableView == tableView) {
NSNumber *object = [NSNumber numberWithInt:indexPath.section];
if (indexPath.row == 0 ) {
if ([sectionHeaderHover containsObject:object]) {
return 150;
} else {
return 0;
}
}
}
return -1;
}
UITableView 系统默认Head会悬停,在不需要这个特效时,可以采用scroll滑动的位置来进行确认是否偏移
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
// if (scrollView == self.myTableView)
{
//YOUR_HEIGHT 为最高的那个headerView的高度
// CGFloat sectionHeaderHeight = 20;
if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}
测试例子:http://download.youkuaiyun.com/detail/huang3838438/7785763