UI页面视图控制器滚动不会向后滚动

时间:2015-04-23 09:53:19

标签: ios objective-c xcode uipageviewcontroller infinite-scroll

我已经实现了一个UIPageViewController,我希望能够无限向右滚动(如用户向左滑动),并能够向另一个方向向后滚动到开头。但是我不希望用户能够在第一页上向左滚动(如用户滑动到右侧),即使我只有三个循环页面,我该怎么办呢?

我已经想出了如何使用右侧的三个视图控制器进行无限滚动(如用户向左滚动)但当用户尝试向左滚动时(如用户向右滑动)错了,屏幕变白了?

任何人都可以对此代码进行改进,以便用户可以无限滚动两种方式,而不仅仅是一种方式吗?如果可能的话,阻止用户在第一个面板上向后滚动?感谢。

PageViewController.h

#import <UIKit/UIKit.h>

@interface PageViewController : UIPageViewController
 <UIPageViewControllerDelegate, UIPageViewControllerDataSource>
@end

PageViewController.m

 #import "PageViewController.h"

@interface PageViewController ()

@end

@implementation PageViewController
{
    NSArray *myViewControllers;


}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.delegate = self;
    self.dataSource = self;

    UIViewController *p1 = [self.storyboard
                            instantiateViewControllerWithIdentifier:@"ContentViewController1"];
    UIViewController *p2 = [self.storyboard
                            instantiateViewControllerWithIdentifier:@"ContentViewController2"];
    UIViewController *p3 = [self.storyboard
                            instantiateViewControllerWithIdentifier:@"ContentViewController3"];

    myViewControllers = @[p1,p2,p3];

    [self setViewControllers:@[p1]
                   direction:UIPageViewControllerNavigationDirectionForward
                    animated:NO completion:nil];


    NSLog(@"loaded!");

}

-(UIViewController *)viewControllerAtIndex:(NSUInteger)index
{
    return myViewControllers[index];
}

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
     viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [myViewControllers indexOfObject:viewController];

    --currentIndex;
    currentIndex = currentIndex % (myViewControllers.count);
    return [myViewControllers objectAtIndex:currentIndex];
}

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [myViewControllers indexOfObject:viewController];

    ++currentIndex;
    currentIndex = currentIndex % (myViewControllers.count);
    return [myViewControllers objectAtIndex:currentIndex];
}


-(NSInteger)presentationCountForPageViewController:
(UIPageViewController *)pageViewController
{
    return myViewControllers.count;
}

-(NSInteger)presentationIndexForPageViewController:
(UIPageViewController *)pageViewController
{
    return 0;
}

@end

1 个答案:

答案 0 :(得分:0)

您可以使用Flag来了解初始视图(第一个视图)。然后使用此滚动启用和禁用方法来阻止滑动。

-(void)setScrollEnabled:(BOOL)enabled forPageViewController:(UIPageViewController*)pageViewController{
for(UIView* view in pageViewController.view.subviews){
    if([view isKindOfClass:[UIScrollView class]]){
        UIScrollView* scrollView=(UIScrollView*)view;
        [scrollView setScrollEnabled:enabled];
        return;
    }
}

希望这会起作用。