检测在pagingEnabled UIScrollView中显示哪个UIView

时间:2011-07-26 15:28:27

标签: iphone objective-c ios xcode cocoa-touch

我正在使用this tutorial中的代码创建一个允许滚动页面的UIScrollView。换句话说,用户可以拖动屏幕从一个UIView切换到另一个UIView。代码基本上如下所示:

- (void)loadView {
[super loadView];
self.view.backgroundColor = [UIColor redColor];
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSInteger numberOfViews = 3;
for (int i = 0; i < numberOfViews; i++) {
CGFloat yOrigin = i * self.view.frame.size.width;
UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
[scroll addSubview:awesomeView];
[awesomeView release];
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:scroll];
[scroll release];
}

我的问题是如何检测用户所在的页面?比如第1页记录“1”,第2页记录“2”等。

谢谢!

3 个答案:

答案 0 :(得分:3)

您可以使用滚动视图的内容偏移量及其宽度来获取当前页码。

int currentPage = (scrollView.contentOffset.x / scrollView.frame.width) + 1;
NSLog(@"current page: %d", currentPage);

如果滚动是垂直完成的,您应该考虑y偏移量。

答案 1 :(得分:1)

如果你想知道用户在滚动时在哪个页面上你应该将你的对象添加为Delegate对象(UIScrollViewDelegate),那么你可以使用

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

在emptystacks回答中调用并计算页面。

顺便说一句。计算是浮点数,如果你需要知道页面完全滚动的时间,你应该使用float。

答案 2 :(得分:1)

实际上,使用int currentPage =(scrollView.contentOffset.x / scrollView.frame.width)+ 1.5;

更好

额外的.5表示页面在视图中途而不是向左舍入时发生页面更改。

相关问题