UICollectionView中的cell包含UIScrollview
需求:在scrollview的子View不为0,当scrollview的展示的index不为0且向右滑动CollectionView。CollectionView不滑动Cell,而是让scrollview切换内容,想左滑同理。
开始真的难到我了。后来在CollectionView上添加了一个滑动手势,代替自带的滑动手势。
UIPanGestureRecognizer *ges = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(mainViewGes:)]; ges.delegate =self; [_mainView addGestureRecognizer:ges
MainView即UICollectionView
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{ //用自定义的手势覆盖collectionView自带的手势 return YES; }
重新这个方法。
- (void)mainViewGes:(UIPanGestureRecognizer *)ges{ if (ges.state == UIGestureRecognizerStateChanged) { // [self commitTranslation:[ges translationInView:self.view]]; }else if (ges.state == UIGestureRecognizerStateBegan){ // NSLog(@"UIGestureRecognizerStateBegan"); }else if (ges.state == UIGestureRecognizerStateEnded){ // NSLog(@"UIGestureRecognizerStateEnded"); [self commitTranslation:[ges translationInView:self.view]]; } } /** 判断手势方向 */ - (void)commitTranslation:(CGPoint)translation { CGFloat absX = fabs(translation.x); CGFloat absY = fabs(translation.y); // 设置滑动有效距离 if (MAX(absX, absY) < 50) return; if (absX > absY ) { if (translation.x < 0) {//向左滑动 if (self.page.sentences.count > 1 && self.sentenceIndex + 1 < self.page.sentences.count) { //想左滑动时,如果句子不是最后一个句子,那么是滑动句子 [self.currentCell.bottomView setContentOffset:CGPointMake(self.currentCell.bottomView.frame.size.width * (self.sentenceIndex + 1), 0) animated:YES]; }else{ if (self.sentenceIndex + 1 == self.page.sentences.count) { //如果向左滑动时,句子是最后一个句子,那么是滑动page if (self.pageNumber + 1 != self.currentCopyModel.pages.count) { [self.mainView setContentOffset:CGPointMake(screen_width * (self.pageNumber + 1), 0) animated:YES]; } } } }else{//向右滑动 if (self.page.sentences.count > 1 && self.sentenceIndex > 0) { //当sentence不是第一个时,向右滑动是滑动句子 [self.currentCell.bottomView setContentOffset:CGPointMake(self.currentCell.bottomView.frame.size.width * (self.sentenceIndex - 1), 0) animated:YES]; }else{ //当sentence为第一个时。滑动就变成了滑动page if (self.sentenceIndex == 0) { if (self.pageNumber != 0) { [self.mainView setContentOffset:CGPointMake(screen_width * (self.pageNumber-1), 0) animated:YES]; } } } } } else if (absY > absX) { if (translation.y<0) {//向上滑动 }else{ //向下滑动 } } }
最后结果就是滑动手势结束之后才判断手势方向,然后手动调用CollectionView或Scrollview的setContenOffset方法。
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
然后会在这个协议里接收到方法。进行处理
此外还有一个跟👆类似的方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
都是滑动动画结束时调用,区别官方注释挺清晰 = =
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView; // called when setContentOffset/scrollRectVisible:animated: finishes. not called if not animating
scrollViewDidEndScrollingAnimation方法是手动调用方法,停止动画后调用,
scrollViewDidEndDecelerating是手滑动操作后停止滑动后调用