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

时间:2013-05-28 09:35:48

标签: ios uiviewcontroller uiscrollview subview

我对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];
   }
}

现在效果很好。但是我为每个子视图都有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];

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

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

1 个答案:

答案 0 :(得分:15)

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

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

UIScrollView设置为contentSize 3倍的边界宽度。确保打开分页并反弹。

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

在ViewController中还有一个名为_contentViews的数组 包含您的UIViews ABC。

然后执行此操作,这将重置内容偏移并在滚动视图到达边缘的同时移动子视图:

-(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)];
    }
}
相关问题