UICollectionView取消滚动,添加翻页效果

562 阅读1分钟

首先取消collectionView自带panGestureRecognizer,可以通过设置其enbale或者collectionView的scrollEnabled属性。

第二步,在cell中添加UIPanGestureRecognizer手势,实现动画

存在问题:
-选择在UICollectionView里给cell添加动画还是在cell中为子视图添加动画?
    选择在cell中,原因是,collectionView中为cell生成动画的时候会因为cell复用的
    原因造成动画效果不显示。
-不添加新手势,在panGestureRecognizer基础上添加新的action不可以,原因是enbale或scrollEnabled
设置为NO时,新的action会受到影响



cell的代理方法实现,view为动画展示的视图
- (void)panGesture:(UIPanGestureRecognizer *)panGes animatedView:(UIView *)view{    CGPoint point = [panGes translationInView:panGes.view];    if (panGes.state == UIGestureRecognizerStateEnded) {        CGPoint offset = self.collectionView.contentOffset;        CGRect toRec = view.bounds;        if (point.x<0) {            //向左滑动            offset.x+=ScreenWidth;            if (offset.x>=self.collectionView.contentSize.width) {                return;            }            toRec.origin.x -=ScreenWidth;        }else {            //向右滑动            offset.x-=ScreenWidth;            if (offset.x<-10) {                return;            }            toRec.origin.x +=ScreenWidth;        }               CGRect frame=view.frame;        frame.origin=CGPointZero;        __block  UIImageView *imgView=[[UIImageView alloc ] initWithFrame:frame];        UIGraphicsBeginImageContext(view.frame.size);        CGContextRef context = UIGraphicsGetCurrentContext();        [view.layer renderInContext:context];        UIImage *cellImage = UIGraphicsGetImageFromCurrentImageContext();        UIGraphicsEndImageContext();        imgView.image=cellImage;        [self.view addSubview:imgView];        self.collectionView.contentOffset =offset;        [UIView animateWithDuration:0.35 animations:^{            imgView.frame=toRec;            imgView.alpha=0;        } completion:^(BOOL finished) {             [imgView removeFromSuperview];            imgView =nil;        }];    }
}