教你做一个可折叠的TableView

作者: Msoso | 来源:发表于2018-03-11 20:21 被阅读2101次
  • 写在开头

首先,膜拜一下这位大神,Ramotion,自从在github上看到这个动画,惊为天人。

心里不禁感叹,原来动画还可以这样做,可能是技术限制了我的想象力。


于是乎,就一头扎进了这个项目里,看到issue里有很多人提出想要一个Tutorial和OC版本,决定边研究源码,边写一个OC版本,毕竟代码还是要自己码一遍可以学的更快。文章结尾会放出OC版本的链接,如果想要swift版本的Demo,可以直接去这位大神的Git下载。

  • 如何使用

  1. 先自建一个TableViewCell,父类为提供的FoldCell。
    @interface DemoFoldingCell : HSFolderCell

  2. 初始化你的TableViewCell时,设置折叠动画的次数以及foregroundViewcontainerView。你所有的界面都是在这两个View里显示的。然后运行父类的commonInit方法。

        self.itemCount = 4;
        self.foregroundView = [self createForegroundView];
        self.containerView = [self createContainerView];
        
        [self commonInit];

foregroundView:这个View是你的cell收起来的时候展示的,就像这样:


containerView:这是当你的cell展开时用于展示的,像这样:

需要注意的是,如果你的折叠次数为两次,那么这个View的高度应为foregroundView的两倍,如果超过两次,那么高度需要满足这个条件:

CGFloat itemHeight = (containerViewSize.height - 2 * foregroundViewSize.height) / (self.itemCount - 2); 
    if(self.itemCount == 2){
        // decrease containerView height or increase itemCount
        NSAssert(containerViewSize.height - 2 * foregroundViewSize.height == 0, @"containerView.height too high");
    }else{
        // decrease containerView height or increase itemCount
        NSAssert(containerViewSize.height - 2 * foregroundViewSize.height >= itemHeight, @"containerView.height too high");
    }
  1. 在TableView的didSelect方法里,调用unfold方法进行动画展示。
    if([self.itemHeight[indexPath.row] floatValue] == closeHeight){
        //open cell
        self.itemHeight[indexPath.row] = [NSNumber numberWithFloat:openHeight];
        [cell unfold:YES animated:YES completion:nil];
        duration = 0.5;
    }else{
        //close cell
        self.itemHeight[indexPath.row] = [NSNumber numberWithFloat:closeHeight];
        [cell unfold:NO animated:YES completion:nil];
        duration = 1.1;
    }
    
    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [tableView beginUpdates];
        [tableView endUpdates];
    } completion:nil];
有几点要注意的:
  1. iOS11以后,TableView有时候会乱跳,需要设置
 _tableView.estimatedRowHeight = 0;
 _tableView.estimatedSectionHeaderHeight = 0;
 _tableView.estimatedSectionFooterHeight = 0;
  1. 需要实现willDisplayCell方法,否则在滑动过程会因为Cell复用而出现错乱。
    if([self.itemHeight[indexPath.row] floatValue] == closeHeight){
        [(DemoFoldingCell *)cell unfold:NO animated:NO completion:nil];
    } else {
        [(DemoFoldingCell *)cell unfold:YES animated:NO completion:nil];
    }
  1. 一定要将两个View的Top类型的Constraint设定到Cell提供的两个属性上,像这样:
NSLayoutConstraint * topConstraint = [NSLayoutConstraint constraintWithItem:foregroundView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTop multiplier:1 constant:8];
self.foregroundViewTop = topConstraint;
//
NSLayoutConstraint * topConstraint = [NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTop multiplier:1 constant:181];
self.containerViewTop = topConstraint;
  • 原理解析

我一直认为,要理清代码,就要跟着代码走一遍,自己码一遍,这样才能体会到每一个地方的作用。另外,这里我贴的是我自己改过后的OC代码,想看Swift版本的,可以去这位大神的Git上下载,我在文章开头贴了链接。

先感叹一下,Swift在很多情况下,真的是要比OC方便太多,举几个代码里的例子:

        for case let itemView as RotatedView in animationView.subviews.filter({ $0 is RotatedView }).sorted(by: { $0.tag < $1.tag }) {
            rotatedViews.append(itemView)
            if let backView = itemView.backView {
                rotatedViews.append(backView)
            }
        }

这里Swift只用了一句话,就对animationVIew的subview数组进行了过滤,找到了所有为RotatedView的subview,且做了排序。而我写的OC版本是这样:

- (NSArray *)rotatedViewsInAnimationView{
    NSArray * arr = [self.animationView.subviews filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UIView * evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return [evaluatedObject isMemberOfClass:[HSRotatedView class]] && evaluatedObject.tag > 0 && evaluatedObject.tag < self.animationView.subviews.count;
    }]];
    
    return arr;
}

- (NSArray *)sortRotatedViewsInAnimationView{
    NSArray * arr = [self rotatedViewsInAnimationView];
    
    NSArray * sortedArr = [arr sortedArrayUsingComparator:^NSComparisonResult(UIView * obj1, UIView * obj2) {
        if(obj1.tag < obj2.tag){
            return NSOrderedAscending;
        }
        if(obj1.tag > obj2.tag){
            return NSOrderedDescending;
        }
        return NSOrderedSame;
    }];
    
    return sortedArr;
}

别的不多说了,来看代码吧!

最开始是在commonInit方法里调用了configureDefaultState方法,方法里对两个TopConstraint属性是否赋值做了判断,然后创建了AnimationView。这个View是一层盖在你Cell上的View,当你Cell折叠起来的时候是不显示的,当展开时显示出来用于做动画。它的约束完全和你的ContainerView的约束一样。

到这里,准备工作就做好了。另外要提一句的是,这里面有一种用于做翻转动画的View,我给它命名为HSRotatedView,它提供了三个方法:

- (CATransform3D)transform3d;

- (void)addBackView:(CGFloat)height color:(UIColor *)color;

- (void)foldingAnimation:(NSString *)timing from:(CGFloat)from to:(CGFloat)to duration:(NSTimeInterval)duration delay:(NSTimeInterval)delay hidden:(BOOL)hidden;

transform3d是返回一个transform3D实例,并且设定了m34值,这样才能看到3d动画。addBackView方法是为该RotatedView添加一个背部view,当你的cell展开或者折叠时,除了你想给用户看到的view以外,翻转后背部的view也应该呈现出来,这里我们的背部view就是一个单纯颜色的view。最后一个方法就是折叠动画了。
还有一个文件是UIView的category,用于截出特定位置的画面。

当我们选择某个Cell执行unfold方法时,比如展开Cell,会先执行addImageItemsToAnimationView方法。简单来说,就是通过截屏的方法,将你的containerView分部分截出来,包括你的所需要创建的背部view,每一个都设定好属性,然后加到animationView上去。接着调用createAnimationItemView方法,将所有刚才创建的view都加入到数组里。
最后就是按顺序一个个执行动画了,我放慢了动画效果,可以看一下:


最后调皮一下,作者有一波操作没看懂,首先是把subView命名为superView,然后这个循环...可能技术又限制了我的想象力,这是源码代码:

        guard let animationViewSuperView = animationView?.subviews else {
            fatalError()
        }

        if animationType == .open {
            for view in animationViewSuperView.filter({ $0 is RotatedView }) {
                view.alpha = 0
            }
        } else {
            for case let view as RotatedView in animationViewSuperView.filter({ $0 is RotatedView }) {
                if animationType == .open {
                    view.alpha = 0
                } else {
                    view.alpha = 1
                    view.backView?.alpha = 0
                }
            }
        }

这是我改了之后的循环:

    for (HSRotatedView * view in arr) {
        if(animationType == AnimationTypeOpen){
            view.alpha = 0;
        }else{
            view.alpha = 1;
            view.backView.alpha = 0;
        }
        
    }
  • Demo

附上我自己写的OC链接啦,喜欢的可以点个star。
HSFolderCellDemo

相关文章

网友评论

  • Xavier_Lost:没有说出具体的实现思路:joy:
  • 江山此夜寒:大神,我swift中cell纯代码怎么写,能教教吗?我照着那位大神写的,崩溃了
  • 叶小合:谢谢大神辛苦code,不过cell层次重叠的情况真实存在:grin:
    Msoso:@叶小合 我看了下重叠是因为上面需要盖一层animationview做动画,官方的也是重叠的
    Msoso:@叶小合 回头我看看:sweat_smile::sweat_smile::sweat_smile:
  • Insight_:连点的bug怎么解决一下
    Insight_:@garfieldxixixi 对的
    b5d6eec712a0:@Msoso 当你快速对一个cell连点时,展开cell不收缩
    Msoso:@missConverse 可否详细说一下什么bug
  • 30ae4723426f:效果不错 就是有点重叠 不太美
  • 西门吸雪:demo 中cell的重用没有处理好,有层叠多层的情况。评论无法发截图,你一看层次图就知道这个情况了。
  • YungFan:效果很炫 这样就可以显示详情了 不用跳转再显示了
  • Development小白zz:这是android端的还是iOS端的
    就是很随意哦:https://github.com/Ramotion/folding-cell-android 安卓也有
    Msoso:@姜小白zz iOS的
  • 族卡巫:666我也是看了这个swift版本的,自己想写个oc的,但做出来的效果总不是很好。学习了:+1:
    Msoso:@西门吸雪 我开头有给swift版本的链接
    西门吸雪:swift版本的链接能否发过来?
    Msoso:@族卡巫 互相学习:grin:
  • shengyang:有没有Obj-C的源码吗
    Msoso:@谢升阳 有啊,结尾给了guthub链接
  • ETHANAIR:666
    Msoso:@ETHANAIR :grin::grin::grin:

本文标题:教你做一个可折叠的TableView

本文链接:https://www.haomeiwen.com/subject/cdqufftx.html