我对 ScrollView 中的无限分页有疑问。在我的应用程序中,ScrollView 中只有 3 个 subview 。每个 subview 都是从 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];
}
}
现在可以正常使用了。但是我为每个 subview 都有 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 View 有一个副本,所以现在我有 5 个 Controller 而不是 3 个。如果我想向 A View 中添加一些内容,我也必须将它添加到 A View 的副本中。
有没有办法用一个 Controller 控制 View A 和 A 的副本,这样我就不必为一个 Controller 创建两个实例?谢谢。
最佳答案
更好的是,您不需要重复 View A 和重复 View C,您只需在 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
中移动它们,同时操作 >contentOffset
.
设置:可能与您已经完成的非常相似。
将您的 UIScrollView
设置为 contentSize
其边界宽度的 3 倍。确保分页已打开并弹回。
将您的 ABC subview 从左到右添加到 UIScrollView。
在您的 ViewController 中还有一个名为 _contentViews
的数组
包含您的 UIViews
ABC。
然后执行此操作,这将重置内容偏移量并在 ScrollView 到达边缘时同时移动您的 subview :
-(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)];
}
}
关于iOS:ScrollView 无限分页 - 重复的端盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16788657/