内容偏移保持不变

时间:2016-01-27 09:10:32

标签: ios objective-c uiscrollview uipageviewcontroller

我的应用中有一个UIPageViewController,设置如下:

self.pageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainPageViewController"];
self.pageViewController.dataSource = self;
self.pageViewController.delegate = self;
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];

我已将UIViewController符合UIScrollViewDelegate并添加了此代码以将scrollView委托设置为self

    for (UIView *currentView in self.pageViewController.view.subviews) {
    if ([currentView isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)currentView;
        scrollView.delegate = self;
        break;
    }
}

然后我尝试使用此方法查找当前页面,但每当我滚动contentOffsetUIPageViewController保持不变:

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
CGFloat pageWidth = scrollView.frame.size.width;
NSInteger page = scrollView.contentOffset.x / pageWidth;

NSLog(@"Content offset.x: %.f", scrollView.contentOffset.x);
}

为什么会这样?

1 个答案:

答案 0 :(得分:3)

我使用UIPageViewController的委托方法而不是scrollView使其工作。这是我的解决方案:

-(void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if (completed) {
        NSInteger currentIndex = [self.navViewControllers indexOfObject:pageViewController.viewControllers[0]];
    }
}