iOS:ScrollView无限分页 - 重复的端盖

Dan*_*elH 5 subview uiscrollview uiviewcontroller ios

我有一个关于ScrollView中无限分页的问题.在我的应用程序中,我在ScrollView中只有3个子视图.每个子视图都是从xib文件加载的.通常它在ScrollView中看起来像ABC.我想进行无限分页,所以我添加了端盖,现在它看起来像CABCA.如果用户在第一个C上,它会跳转到常规C,如果用户在最后一个A上,它会跳转到常规A.这是一个代码:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)sender {

  if (scrollView.contentOffset.x == 0)
  {
      [scrollView scrollRectToVisible:CGRectMake
      ((scrollView.frame.size.width * 3), 0,
      scrollView.frame.size.width,
      scrollView.frame.size.height) animated:NO];
  } 
  else if (scrollView.contentOffset.x == scrollView.frame.size.width * 4)
  {
     [scrollView scrollRectToVisible:CGRectMake
     (scrollView.frame.size.width, 0,
      scrollView.frame.size.width,
      scrollView.frame.size.height) animated:NO];
   }
}
Run Code Online (Sandbox Code Playgroud)

它现在完美运作.但是我为每个子视图都有ViewController,这就是我将它们添加到ScrollView的方式:

  subViewController1 = [[SubViewController1 alloc] initWithNibName:@"SubView" bundle:nil];
  subViewController1.view.frame =
    CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height);
  [scrollView addSubview:subViewController1.view];
Run Code Online (Sandbox Code Playgroud)

问题是A和C视图有一个重复,所以现在我有5个控制器而不是3.如果我想在A视图中添加一些内容,我必须将它添加到A视图的副本中.

有没有办法如何使用一个控制器控制视图A和A的副本,所以我不必创建一个控制器的两个实例?谢谢.

Mik*_*ard 15

更好的是,您不需要具有重复的视图A和重复的视图C,您只需在- (void)scrollViewDidScroll:(UIScrollView *)scrollView操作时 移动它们contentOffset.

设置:可能与您已经完成的方式非常相似.

设置你的宽度UIScrollViewcontentSize3倍.确保打开分页并反弹.

从左到右将您的ABC子视图添加到UIScrollView.

您的ViewController中还有一个_contentViews 包含UIViewsABC 的数组.

然后实现这将重置内容偏移并在滚动视图到达边缘的同时移动子视图:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if(scrollView.contentOffset.x == 0) {
        CGPoint newOffset = CGPointMake(scrollView.bounds.size.width+scrollView.contentOffset.x, scrollView.contentOffset.y);
        [scrollView setContentOffset:newOffset];
        [self rotateViewsRight];
    }
    else if(scrollView.contentOffset.x == scrollView.bounds.size.width*2) {
        CGPoint newOffset = CGPointMake(scrollView.contentOffset.x-scrollView.bounds.size.width, scrollView.contentOffset.y);
        [scrollView setContentOffset:newOffset];
        [self rotateViewsLeft];
    }
}

-(void)rotateViewsRight {
    UIView *endView = [_contentViews lastObject];
    [_contentViews removeLastObject];
    [_contentViews insertObject:endView atIndex:0];
    [self setContentViewFrames];

}

-(void)rotateViewsLeft {
    UIView *endView = _contentViews[0];
    [_contentViews removeObjectAtIndex:0];
    [_contentViews addObject:endView];
    [self setContentViewFrames];

}

-(void) setContentViewFrames {
    for(int i = 0; i < 3; i++) {
        UIView * view = _contentViews[i];
        [view setFrame:CGRectMake(self.view.bounds.size.width*i, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    }
}
Run Code Online (Sandbox Code Playgroud)