iphone - 检测在 pagingEnabled UIScrollView 中显示的是哪个 UIView

标签 iphone objective-c ios xcode cocoa-touch

我正在使用 this tutorial 中的代码创建一个允许滚动页面的 UIScrollView。换句话说,用户可以拖动屏幕从一个 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”等。

谢谢!

最佳答案

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

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

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

关于iphone - 检测在 pagingEnabled UIScrollView 中显示的是哪个 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6832542/

相关文章:

ios - 如何在 iOS 应用程序中加载初始 UIViewController?

iphone - 如何释放由 arrayWithContentsOfURL 加载的 NSArray 的元素?

ios - 如何从NSString获取NSTimeInterval?

ios - Xcode 8 : Archive build fails (for nested frameworks) with link errors. 常规构建编译成功

ios - 核心数据迁移错误 Cocoa error 134130 Can't find model for source store

ios - 使用多部分请求上传文件 - Swift 4

iphone - 更新后,UI 标签值在 TableView 中重叠

iOS:放大/缩小动画以显示 UIView

ios - UIKit Dynamics/Blocks - 完成时删除 UIPushBehavior

iPhone架构