iOS - UIPageViewController的使用

作用

切換多個vc(控制器) 的controller.其每一個單元,稱為一頁:page.在一個page中,可以添加一個vc, 也可以添加2個vc, 如果添加2個vc, 其展示的效果是分欄效果.

切換控制器方法, 只有調(diào)用這個方法才能切換
- (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個子控制器加載數(shù)據(jù)的時機是: 為將顯示的vc設(shè)置參數(shù)時.

代碼

1.設(shè)置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];
        
        //區(qū)域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.設(shè)置 UIPageViewController,及相應(yīng)的方法


- (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;
    
    //是否與當(dāng)前索引相等,不相等則滾動
    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]];
        }];
    }
}

///設(shè)置選中按鈕的狀態(tài),添加子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傳遞參數(shù). 子vc中有自己的處理:如果參數(shù)有變化,便會加載數(shù)據(jù).

- (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.實現(xiàn)UIPageController 的數(shù)據(jù)源

#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 加載數(shù)據(jù)

注: 此處不會重復(fù)加載, 如上述, 因為子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. 在下代理方法中處理切換時的細(xì)節(jié), 更新相應(yīng)按鈕的選中狀態(tài)及設(shè)置 pageControl 的 currentPage.

此時要注意這種情況: 用戶左右輕微切換界面, 但是并沒有切換到相應(yīng)的界面.

/**
 *  此代理方法僅在手指drag時,才會調(diào)用.代碼設(shè)置,不會調(diào)用.
 *
 *  @param pageViewController      當(dāng)前UIPageViewController
 *  @param finished                動畫是否結(jié)束
 *  @param previousViewControllers 拖動開始前的vc.如果從控制器src拖動到控制器des,則為src;如果沒有成功拖動到des,即拖動了一點點,又返回到src,也為src
 *  @param completed               是否完成拖動到控制器des,如果拖動到des,為YES;如果沒有拖動到des,為NO
 *  利用finished與completed參數(shù),可控制代碼執(zhí)行的時機
 */
- (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 的比較

優(yōu)點

  • UIPageViewController 切換界面時, 即使從0跳到10界面, 其動畫UI效果也很友好:只是一個界面的跨度; 而如果使用UICollectionView就只能animated:NO

缺點

  • 因為UIPageViewController沒有將其子view為scrollView的控件暴露出來
  • 不能精確地處理一些跟contentOffset的距離有關(guān)的操作.
  • 或者說要實現(xiàn)精確操作,要做很多工作. 因為需要拿到UIPageViewController的scrollView, 然后設(shè)置其代理.
    這只是我的想法,并沒有實際執(zhí)行.通過NSLog, 可以看到UIPageViewController的view有一個子view, 這個子view的類別是queuingScrollView, 而它繼承自scrollView .
  • UIPageViewController在切換控制器時有bug, 有時沒有切換到正確的界面.
    如框架MBXPageViewControllerFreeButtonsDemo中,(我是在9.2測試)第一次點擊第三個按鈕時,便沒有正確跳轉(zhuǎn).不知作者為什么沒有發(fā)現(xiàn).
  • 出現(xiàn)時機:
    • 滾動方式: UIPageViewControllerTransitionStyleScroll
    • 滾動時 animated:YES

具體可見下鏈接,鏈接中也給出了可能的解決方法:
http://stackoverflow.com/questions/12939280/uipageviewcontroller-navigates-to-wrong-page-with-scroll-transition-style

由于我的demo并沒有出現(xiàn)這個問題,所以暫未深入研究.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容