UIPageViewController的使用

UIPageViewController是一個用來管理內(nèi)容頁之間導航的容器控制器(container view controller),其中每個子頁面由子視圖控制器管理。內(nèi)容頁間導航可以由用戶手勢觸發(fā),也可以由代碼控制。在頁面之間導航時,UIPageViewController使用其初始化時指定的transition style動畫。

在應用程序啟動時,我們可以使用UIPageViewController來實現(xiàn)引導圖的效果,以告知用戶app的基本功能。

這篇文章將講述如何使用UIPageViewController,讓用戶在不同頁面間滑動。

1. 創(chuàng)建demo

創(chuàng)建一個Simple View Application模板的工程,名稱為PageViewController。創(chuàng)建兩個繼承自UIViewController的控制器,名稱分別為RootViewController、DataViewController;另外創(chuàng)建一個名稱為Model繼承自NSObject的類。

Xcode提供了Page-Based App模板,其包含一個基于UIPageViewController的功能齊全的應用程序。但這個模板有點復雜,需要花更多時間來清理模版。除此之外,從頭開始更易于理解UIPageViewController背后的概念。

demo完成后效果如下:

UIPageViewControllerTransitionStyleScroll
UIPageViewControllerTransitionStylePageCurl

2. 頁面布局

進入DataViewController.h文件,在接口部分添加以下屬性:

@interface DataViewController : UIViewController

@property (nonatomic, assign) NSUInteger itemIndex;
@property (nonatomic, strong) NSString *day;
@property (nonatomic, strong) NSString *quote;

@end

進入DataViewController.m文件,聲明兩個UILabel用來顯示頁碼和內(nèi)容,同時使用懶加載初始化,并添加到view,如下:

@interface DataViewController ()

@property (nonatomic, strong) UILabel *dayLabel;
@property (nonatomic, strong) UILabel *quoteLabel;

@end
#pragma mark - Getters & Setters

- (UILabel *)dayLabel {
    if (!_dayLabel) {
        _dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, CGRectGetWidth(self.view.bounds), 20)];
        _dayLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
        _dayLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _dayLabel;
}

- (UILabel *)quoteLabel {
    if (!_quoteLabel) {
        _quoteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 50)];
        _quoteLabel.frame = CGRectInset(_quoteLabel.frame, 16, 0);
        _quoteLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleTitle1];
        _quoteLabel.textAlignment = NSTextAlignmentCenter;
        _quoteLabel.numberOfLines = 0;
    }
    return _quoteLabel;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.dayLabel];
    [self.view addSubview:self.quoteLabel];
}

最后,在viewWillAppear:中將itemIndex、dayquote顯示到UILabel

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.dayLabel.text = [NSString stringWithFormat:@"Page %lu %@",self.itemIndex + 1, [self.day description]];
    self.quoteLabel.text = self.quote;
}

3. UIPageViewControllerDataSource

為支持手勢導航,必須為視圖控制器提供data source,它會根據(jù)需要提供內(nèi)容視圖控制器,data source必須遵守UIPageViewControllerDataSource協(xié)議。

一般,UIPageViewControllerDataSource會根據(jù)傳入的視圖控制器來決定要顯示的內(nèi)容,以此創(chuàng)建所需的視圖控制器。在視圖控制器中添加諸如頁碼之類的信息很有幫助,可以簡化確定顯示內(nèi)容的任務(wù)。

進入Model.h文件,聲明Model類遵守UIPageViewControllerDataSource協(xié)議,并添加以下方法:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class DataViewController;

@interface Model : NSObject <UIPageViewControllerDataSource>

- (DataViewController *)viewControllerAtIndex:(NSUInteger)index;

@end

進入Model.m文件,聲明兩個數(shù)組,用于每頁顯示的內(nèi)容,如下:

@interface Model ()

@property (nonatomic, strong, readonly) NSArray *days;
@property (nonatomic, strong, readonly) NSArray *quotes;

@end

在初始化方法中,創(chuàng)建數(shù)據(jù)模型:

- (instancetype)init {
    self = [super init];
    if (self) {
        // 創(chuàng)建數(shù)據(jù)模型。
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        _days = [[dateFormatter weekdaySymbols] copy];
        
        _quotes = @[@"Everyone who isn’t us is an enemy.",
                    @"When you play the game of thrones you win or you die. There is no middle ground.",
                    @"You’re a clever man. But you’re not half as clever as you think you are.",
                    @"Nobody cares what your father once told you.",
                    @"Everywhere in the world, they hurt little girls.",
                    @"I choose violence.",
                    @"What is Dead May Never Die"
                    ];
    }
    return self;
}

實現(xiàn)接口部分聲明的方法:

- (DataViewController *)viewControllerAtIndex:(NSUInteger)index {
    // 返回指定index的視圖控制器。
    if (self.days.count == 0 || index >= self.days.count) {
        return nil;
    }
    
    DataViewController *dataVC = [[DataViewController alloc] init];
    dataVC.itemIndex = index;
    dataVC.day = self.days[index];
    dataVC.quote = self.quotes[index];
    return dataVC;
}

UIPageViewControllerDataSource協(xié)議共有四個方法,其中pageViewController:viewControllerBeforeViewController:方法和pageViewController:viewControllerAfterViewController方法必須實現(xiàn)。

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    // 返回上一個視圖控制器。
    NSUInteger index = ((DataViewController *)viewController).itemIndex;
    if (index == 0 || index == NSNotFound) {
        return nil;
    }
    
    --index;
    return [self viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    // 返回下一個視圖控制器。
    NSUInteger index = ((DataViewController *)viewController).itemIndex;
    if (index == self.days.count - 1 || index == NSNotFound) {
        return nil;
    }
    
    ++index;
    return [self viewControllerAtIndex:index];
}

如果同時實現(xiàn)了presentationCountForPageViewController:presentationIndexForPageViewController:可選實現(xiàn)協(xié)議方法,同時UIPageViewController的transition style被指定為UIPageViewControllerTransitionStyleScroll,navigationOrientation被指定為UIPageViewControllerNavigationOrientationHorizontal,則會在視圖控制器底部顯示page indicator。

// 初始頁。
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
    NSUInteger currentPage = 2;
    
    if (currentPage >= self.days.count) {
        currentPage = 0;
    }
    
    DataViewController *dataVC = (DataViewController *)pageViewController.viewControllers.firstObject;
    dataVC.itemIndex = currentPage;
    dataVC.day = self.days[currentPage];
    dataVC.quote = self.quotes[currentPage];
    return currentPage;
}

// 共多少頁。
- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController {
    return self.days.count;
}

如果默認顯示第一頁,則presentationIndexForPageViewController:方法可以直接返回0,而無需做其他操作。

在調(diào)用setViewControllers:direction:animated:completioin:方法后,會調(diào)用上面配置page control的方法。通過手勢在頁面間導航時,將不再調(diào)用上述方法,currentPage的index會被自動更新,視圖控制器的數(shù)量應為常量。

4. 配置UIPageViewController

進入RootViewController.m文件,聲明一個UIPageViewController類型的屬性,另外聲明一個Model類型的實例。

#import "RootViewController.h"
#import "DataViewController.h"
#import "Model.h"

@interface RootViewController () 

@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, strong) Model *model;

@end

記得導入DataViewControllerModel類。

viewDidLoad方法中配置UIPageViewController,更新后如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化并配置pageViewController。
    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                          navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                        options:@{UIPageViewControllerOptionInterPageSpacingKey : @20}];
    DataViewController *dataVC = [self.model viewControllerAtIndex:0];
    [self.pageViewController setViewControllers:@[dataVC]
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:YES
                                     completion:nil];
    
    // 設(shè)置代理。
    self.pageViewController.dataSource = self.model;
    self.pageViewController.delegate = self;
    
    // 設(shè)置pageViewController inset。
    CGRect pageViewRect = self.view.bounds;
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        pageViewRect = CGRectInset(pageViewRect, 40, 40);
    }
    self.pageViewController.view.frame = pageViewRect;
    
    // 添加視圖控制器、視圖。
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    
    [self.pageViewController didMoveToParentViewController:self];
    
    // 設(shè)置page indicator顏色。
    UIPageControl *pagecontrol = UIPageControl.appearance;
    pagecontrol.pageIndicatorTintColor = [UIColor lightGrayColor];
    pagecontrol.currentPageIndicatorTintColor = [UIColor darkGrayColor];
}

// 初始化model
- (Model *)model {
    if (!_model) {
        _model = [[Model alloc] init];
    }
    return _model;
}

initWithTransitionStyle:navigationOrientation:options:方法用來初始化UIPageViewController,其參數(shù)如下:

  • transition style參數(shù):可以為滾動樣式UIPageViewControllerTransitionStyleScroll和翻頁樣式UIPageViewControllerTransitionPageCurl。

  • navigationOrientation:可以為橫向UIPageViewControllerNavigationOrientationHorizontal和縱向UIPageViewControllerNavigationOrientationVertical

  • options:該參數(shù)為詞典。key為UIPageViewControllerOptionInterPageSpacingKeyUIPageViewControllerOptionSpineLocationKey

    • Key為UIPageViewControllerOptionInterPageSpacingKey時,值應為封裝在NSNumber中的CGFloat類型。默認值為0。只有在transition style為UIPageViewControllerTransitionStyleScroll時才會生效。

    • Key為UIPageViewControllerOptionSpineLocationKey時,值為以下枚舉類型:

      typedef enum UIPageViewControllerSpineLocation : NSInteger {
          UIPageViewControllerSpineLocationNone = 0,
          UIPageViewControllerSpineLocationMin = 1,
          UIPageViewControllerSpineLocationMid = 2,
          UIPageViewControllerSpineLocationMax = 3
      } UIPageViewControllerSpineLocation;
      

當transition style為UIPageViewControllerTransitionPageCurl時,該值默認為UIPageViewControllerSpineLocationMin;否則,該值默認為UIPageViewControllerSpineLocationNone。另外,使用該值時應當將其封裝在NSNumber對象中使用。

初始化UIPageViewController后,使用setViewControllers:direction:animated:completion:方法設(shè)置其內(nèi)容視圖??梢灾付ㄒ淮物@示一個或兩個視圖控制器,其由spineLocation、doubleSided屬性決定。動畫結(jié)束后將顯示傳遞給該方法的viewControllers。如果transition style為UIPageViewControllerTransitionStylePageCurl,傳遞給該方法的viewControllers將由spineLocation、doubleSided屬性決定。

spineLocation doubleSided viewControllers參數(shù)
UIPageViewControllerSpineLocationMid YES 傳入左側(cè)和右側(cè)需要顯示的視圖控制器
UIPageViewControllerSpineLocationMin

UIPageViewControllerSpineLocationMax
YES 傳入正面、背面兩側(cè)顯示的視圖控制器。

背面視圖控制用于翻頁動畫
UIPageViewControllerSpineLocationMin

UIPageViewControllerSpineLocationMax
NO 傳入正面需要顯示的視圖控制器

5. UIPageViewControllerDelegate

UIPageViewController的委托必須遵守UIPageViewControllerDelegete協(xié)議,該協(xié)議中的方法允許委托在設(shè)備方向改變、用戶導航到新頁面時接收通知。對于page-curl style transition,可以在用戶界面改變時提供不同的脊柱位置(spine location)。

RootViewController.m文件中,添加兩個NSUInteger類型的屬性,分別用來保存當前頁碼、下一頁碼。

@interface RootViewController () <UIPageViewControllerDelegate>

...
@property (nonatomic, assign) NSUInteger currentIndex;
@property (nonatomic, assign) NSUInteger nextIndex;

@end

實現(xiàn)UIPageViewControllerDelegete的協(xié)議方法,在用戶滑動時更新頁面內(nèi)容:

// 手勢導航開始前調(diào)用該方法。
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    // 如果用戶終止了滑動導航,transition將不能完成,頁面也將保持不變。
    
    DataViewController *dataVC = (DataViewController *)pendingViewControllers.firstObject;
    if (dataVC) {
        self.nextIndex = dataVC.itemIndex;
        
        // 輸出滑動方向
        if (self.currentIndex < self.nextIndex) {
            NSLog(@"Forward");
        } else {
            NSLog(@"Backward");
        }
    }
}

// 手勢導航結(jié)束后調(diào)用該方法。
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    // 使用completed參數(shù)區(qū)分成功導航和中止導航。
    if (completed) {
        self.currentIndex = self.nextIndex;
    }
}

運行demo,滑動上面視圖或點擊底部UIPageControl,如下所示:

Scroll.gif

雖然在初始化時指定了page間距,但上面的gif中并沒有顯示,這是因為RootViewControllerDataViewController背景顏色一致所致,設(shè)置DataViewController視圖背景顏色為brown color,再次運行demo:

UIPageViewControllerOptionInterPageSpacingKey

更新RootViewController.m中的viewDidLoad方法,設(shè)置transition style為page curl:

- (void)viewDidLoad {
    ...
    // page curl
    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
                                                         navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                            options:@{UIPageViewControllerOptionSpineLocationKey : @(UIPageViewControllerSpineLocationMin)}];
    
    ...
}

另外,實現(xiàn)UIPageViewControllerDelegate協(xié)議中的pageViewController: spineLocationForInterfaceOrientation:方法,根據(jù)設(shè)備狀態(tài)調(diào)整spine location。

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
    if (UIInterfaceOrientationIsPortrait(orientation) || ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone)) {
        // 設(shè)備為phone,或portrait狀態(tài)時,設(shè)置UIPageViewControllerSpineLocation為Min。

        DataViewController *currentVC = self.pageViewController.viewControllers.firstObject;
        [self.pageViewController setViewControllers:@[currentVC]
                                          direction:UIPageViewControllerNavigationDirectionForward
                                           animated:YES
                                         completion:nil];
        self.pageViewController.doubleSided = NO;
        return UIPageViewControllerSpineLocationMin;
    } else {
        // 在landscape orientation時,設(shè)置spine為mid,pageViewController展示兩個視圖控制器。

        DataViewController *currentVC = self.pageViewController.viewControllers.firstObject;
        NSUInteger indexOfCurrentVC = currentVC.itemIndex;

        NSArray *viewControllers = [NSArray array];

        if (indexOfCurrentVC == 0 || indexOfCurrentVC % 2 == 0) {
            // 如果當前頁為偶數(shù),則顯示當前頁和下一頁。
            UIViewController *nextVC = [self.model pageViewController:self.pageViewController viewControllerAfterViewController:currentVC];
            viewControllers = @[currentVC, nextVC];
        } else {
            // 如果當前頁為奇數(shù),則顯示上一頁和當前頁。
            UIViewController *previousVC = [self.model pageViewController:self.pageViewController viewControllerBeforeViewController:currentVC];
            viewControllers = @[previousVC, currentVC];
        }
        [self.pageViewController setViewControllers:viewControllers
                                          direction:UIPageViewControllerNavigationDirectionForward
                                           animated:YES
                                         completion:nil];

        return UIPageViewControllerSpineLocationMid;
    }
}

運行demo,如下所示:

UIPageViewControllerOptionSpineLocationKey

另外,UIPageViewControllerDelegate協(xié)議中還有pageViewControllerSupportedInterfaceOrientations:方法,用來指定支持的全部方向。pageViewControllerPreferredInterfaceOrientationForPresentation:方法返回頁面視圖控制器的首選呈現(xiàn)方向。

UIPageViewController類一般原樣使用(used as-is),但也可以繼承。

Demo名稱:PageViewController
源碼地址:https://github.com/pro648/BasicDemos-iOS

參考資料:

  1. UIPageViewController
  2. Get user swiping direction in UIPageViewController

歡迎更多指正:https://github.com/pro648/tips/wiki

最后編輯于
?著作權(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)容