我在PageViewController中有一系列VC,用户可以用手指从左到右导航.我需要添加按钮,这些按钮基本上执行与手指滑动相同的操作,通过VC向左或向右移动一个按钮.我怎样才能做到这一点?现在我使用这两种方法动态设置VC作为用户滑动:
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController; - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController;
如果用户点击按钮,我可以做同样的事吗?
解决方法
您可以使用setViewControllers:direction:animated:completion:在页面视图控制器上以编程方式设置当前显示的视图控制器.
这是一个显示具有随机背景颜色的视图控制器的示例.您可以调整此选项以使用特定的视图控制器.
- (void)viewDidLoad { [super viewDidLoad]; self.pvc = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil]; self.pvc.view.frame = CGRectInset(self.view.bounds,200,200); [self.view addSubview:self.pvc.view]; [self.pvc setViewControllers:@[[self randomVC]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil]; } -(UIViewController*)randomVC { UIViewController *vc = [[UIViewController alloc] init]; UIColor *color = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1]; vc.view.backgroundColor = color; return vc; } - (IBAction)prevIoUsButtonPressed:(id)sender { [self.pvc setViewControllers:@[[self randomVC]] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:nil]; } - (IBAction)nextButtonPressed:(id)sender { [self.pvc setViewControllers:@[[self randomVC]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil]; }