iOS - UIPageViewController的使用

作用

切换多个vc(控制器) 的controller.其每一个单元,称为一页:page.在一个page中,可以添加一个vc, 也可以添加2个vc, 如果添加2个vc, 其展示的效果是分栏效果.

切换控制器方法, 只有调用这个方法才能切换
- (void)setViewControllers:(nullable NSArray<UIViewController *> *)viewControllers direction:(UIPageViewControllerNavigationDirection)direction animated:(BOOL)animated completion:(void (^ __nullable)(BOOL finished))completion;

案例

test.gif

逻辑

  • HomeViewController 为主控制器, 添加一个UIPageViewController: pvc
  • pvc 添加 5个子控制器
  • 5个子控制器都继承了一个控制器 YHManufacHomeVcChildVcParentVc
  • 5个子控制器加载数据的时机是: 为将显示的vc设置参数时.

代码

1.设置5个子vc


- (NSArray<YHManufacHomeVcChildVcParentVc *> *)vcs{
    if (!_vcs) {
        //整体vc
        UIStoryboard *sb = [UIStoryboard storyboardWithName:NSStringFromClass([YHWholeVc class]) bundle:nil];
        YHWholeVc *wholeVc = [sb instantiateInitialViewController];
        
        //排名vc
        sb = [UIStoryboard storyboardWithName:NSStringFromClass([YHRankVc class]) bundle:nil];
        YHRankVc *rankVc = [sb instantiateInitialViewController];
        
        //区域vc
        YHAreaVc *areaVc = [[YHAreaVc alloc] init];
        areaVc.delegate = self;
        
        //品类vc
        YHCategoryVc *categoryVc = [[YHCategoryVc alloc] init];
        categoryVc.delegate = self;
        
        //渠道vc
        YHSourceVc *srcVc = [[YHSourceVc alloc] init];
        srcVc.delegate = self;
        
        self.vcs = @[wholeVc, rankVc, areaVc, categoryVc, srcVc];
    }
    return _vcs;
}

2.设置 UIPageViewController,及相应的方法


- (void)setupPageViewController{
    
    CGFloat scX = 0;
    CGFloat scY = CGRectGetMaxY(self.pgView.frame);
    CGFloat scW = self.view.yh_width;
    CGFloat scH = self.view.yh_height - scY - CGRectGetHeight(self.tabBarController.tabBar.frame);
    CGRect rect = CGRectMake(scX, scY, scW, scH);
    
    NSDictionary *options = @{UIPageViewControllerOptionInterPageSpacingKey : @(20)};
    
    UIPageViewController *pvc = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:options];
    self.pvc = pvc;
    [self.view addSubview:pvc.view];
    pvc.view.frame = rect;
    pvc.dataSource = self;
    pvc.delegate = self;
    
    [self moveToViewNumber:0 animated:YES];
    [self reloadVcData:self.vcs[0]];

}


#pragma mark ------------------------------------------
#pragma mark private method of pvc
- (void)moveToViewNumber:(NSInteger)index animated:(BOOL)animated {
    YHManufacHomeVcChildVcParentVc *vc = (YHManufacHomeVcChildVcParentVc *)self.vcs[index];
    UIPageViewControllerNavigationDirection direction = UIPageViewControllerNavigationDirectionForward;
    
    //是否与当前索引相等,不相等则滚动
    if (self.currentIndex != index) {
        if (self.currentIndex > index) {
            direction = UIPageViewControllerNavigationDirectionReverse;
        }
        
        WeakSelf
        [self.pvc setViewControllers:@[vc] direction:direction animated:animated completion:^(BOOL finished) {
            
            [weakSelf updateCurrentIndex:weakSelf.titleBtnsView.subviews[index]];
        }];
    }
}

///设置选中按钮的状态,添加子vc的view
- (void)updateCurrentIndex:(UIButton *)btn{
    if (self.selectedBtn == btn) {
        return;
    }
    
    //背景
    self.selectedBtn.selected = NO;
    self.selectedBtn.backgroundColor = [UIColor lightGrayColor];
    
    btn.selected = YES;
    self.selectedBtn = btn;
    self.selectedBtn.backgroundColor = YHGlobalColor;
    
    NSInteger index = btn.tag - YHMinTagOfTitleBtn;
    self.pageControl.currentPage = index;
    self.currentIndex = index;
}

3. 为子vc传递参数. 子vc中有自己的处理:如果参数有变化,便会加载数据.

- (void)reloadVcData:(YHManufacHomeVcChildVcParentVc *)vc{
    
    YHWholeDataParam *param = [YHWholeDataParam new];
    param.YearMonth = self.currentDate;
    param.area = [YHArchiveTool shareArchiveTool].loginM.area;
    param.level = [YHArchiveTool shareArchiveTool].loginM.level;
    param.isM = YHReportTypeDaily;
    vc.paramOfData = param;
    
}

4.实现UIPageController 的数据源

#pragma mark ------------------------------------------
#pragma mark UIPageViewControllerDataSource
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
    
    NSUInteger index = [self.vcs indexOfObject:(YHManufacHomeVcChildVcParentVc *)viewController];
    if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }
    index--;
    
    YHManufacHomeVcChildVcParentVc *vc = (YHManufacHomeVcChildVcParentVc *)self.vcs[index];
    return vc;
    
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    
    NSUInteger index = [self.vcs indexOfObject:(YHManufacHomeVcChildVcParentVc *)viewController];;
    if (index == NSNotFound) {
        return nil;
    }
    index++;
    if (index >= YHVcsCount) {
        return nil;
    }
    
    YHManufacHomeVcChildVcParentVc *vc = (YHManufacHomeVcChildVcParentVc *)self.vcs[index];
    return vc;
    
}

5.切换vc时, 使目的vc 加载数据

注: 此处不会重复加载, 如上述, 因为子vc的set方法中有判断.

#pragma mark ------------------------------------------
#pragma mark UIPageViewControllerDelegate
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers{
    
    YHManufacHomeVcChildVcParentVc *vc = (YHManufacHomeVcChildVcParentVc *)pendingViewControllers.firstObject;
    NSInteger index = [self.vcs indexOfObject:vc];

    [self reloadVcData:vc];
    [self updateCurrentIndex:self.titleBtnsView.subviews[index]];
}

6. 在下代理方法中处理切换时的细节, 更新相应按钮的选中状态及设置 pageControl 的 currentPage.

此时要注意这种情况: 用户左右轻微切换界面, 但是并没有切换到相应的界面.

/**
 *  此代理方法仅在手指drag时,才会调用.代码设置,不会调用.
 *
 *  @param pageViewController      当前UIPageViewController
 *  @param finished                动画是否结束
 *  @param previousViewControllers 拖动开始前的vc.如果从控制器src拖动到控制器des,则为src;如果没有成功拖动到des,即拖动了一点点,又返回到src,也为src
 *  @param completed               是否完成拖动到控制器des,如果拖动到des,为YES;如果没有拖动到des,为NO
 *  利用finished与completed参数,可控制代码执行的时机
 */
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{
    
    if (completed){
       
    }else{
        
        YHLog(@"---no completed---%zd: %@", previousViewControllers.count, previousViewControllers.firstObject);
        
        YHManufacHomeVcChildVcParentVc *vc = (YHManufacHomeVcChildVcParentVc *)previousViewControllers.firstObject;
        NSInteger index = [self.vcs indexOfObject:vc];
        
        [self updateCurrentIndex:self.titleBtnsView.subviews[index]];
        
    }
    
}

上面代码使用了UIPageViewController的两个代理方法:

// Sent when a gesture-initiated transition begins.
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers NS_AVAILABLE_IOS(6_0);

// Sent when a gesture-initiated transition ends. The 'finished' parameter indicates whether the animation finished, while the 'completed' parameter indicates whether the transition completed or bailed out (if the user let go early).
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed;

与UICollectionView 的比较

优点

  • UIPageViewController 切换界面时, 即使从0跳到10界面, 其动画UI效果也很友好:只是一个界面的跨度; 而如果使用UICollectionView就只能animated:NO

缺点

  • 因为UIPageViewController没有将其子view为scrollView的控件暴露出来
  • 不能精确地处理一些跟contentOffset的距离有关的操作.
  • 或者说要实现精确操作,要做很多工作. 因为需要拿到UIPageViewController的scrollView, 然后设置其代理.
    这只是我的想法,并没有实际执行.通过NSLog, 可以看到UIPageViewController的view有一个子view, 这个子view的类别是queuingScrollView, 而它继承自scrollView .
  • UIPageViewController在切换控制器时有bug, 有时没有切换到正确的界面.
    如框架MBXPageViewControllerFreeButtonsDemo中,(我是在9.2测试)第一次点击第三个按钮时,便没有正确跳转.不知作者为什么没有发现.
  • 出现时机:
    • 滚动方式: UIPageViewControllerTransitionStyleScroll
    • 滚动时 animated:YES

具体可见下链接,链接中也给出了可能的解决方法:
http://stackoverflow.com/questions/12939280/uipageviewcontroller-navigates-to-wrong-page-with-scroll-transition-style

由于我的demo并没有出现这个问题,所以暂未深入研究.

推荐阅读更多精彩内容