UIPageViewController的使用

UIPageViewController是一个用来管理内容页之间导航的容器控制器(container view controller),其中每个子页面由子视图控制器管理。内容页间导航可以由用户手势触发,也可以由代码控制。在页面之间导航时,UIPageViewController使用其初始化时指定的transition style动画。

在应用程序启动时,我们可以使用UIPageViewController来实现引导图的效果,以告知用户app的基本功能。

这篇文章将讲述如何使用UIPageViewController,让用户在不同页面间滑动。

1. 创建demo

创建一个Simple View Application模板的工程,名称为PageViewController。创建两个继承自UIViewController的控制器,名称分别为RootViewControllerDataViewController;另外创建一个名称为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用来显示页码和内容,同时使用懒加载初始化,并添加到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:中将itemIndexdayquote显示到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,它会根据需要提供内容视图控制器,data source必须遵守UIPageViewControllerDataSource协议。

一般,UIPageViewControllerDataSource会根据传入的视图控制器来决定要显示的内容,以此创建所需的视图控制器。在视图控制器中添加诸如页码之类的信息很有帮助,可以简化确定显示内容的任务。

进入Model.h文件,声明Model类遵守UIPageViewControllerDataSource协议,并添加以下方法:

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

@interface Model : NSObject <UIPageViewControllerDataSource>

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

@end

进入Model.m文件,声明两个数组,用于每页显示的内容,如下:

@interface Model ()

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

@end

在初始化方法中,创建数据模型:

- (instancetype)init {
    self = [super init];
    if (self) {
        // 创建数据模型。
        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;
}

实现接口部分声明的方法:

- (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协议共有四个方法,其中pageViewController:viewControllerBeforeViewController:方法和pageViewController:viewControllerAfterViewController方法必须实现。

- (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];
}

如果同时实现了presentationCountForPageViewController:presentationIndexForPageViewController:可选实现协议方法,同时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,而无需做其他操作。

在调用setViewControllers:direction:animated:completioin:方法后,会调用上面配置page control的方法。通过手势在页面间导航时,将不再调用上述方法,currentPage的index会被自动更新,视图控制器的数量应为常量。

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];
    
    // 设置代理。
    self.pageViewController.dataSource = self.model;
    self.pageViewController.delegate = self;
    
    // 设置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];
    
    // 设置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,其参数如下:

  • transition style参数:可以为滚动样式UIPageViewControllerTransitionStyleScroll和翻页样式UIPageViewControllerTransitionPageCurl

  • navigationOrientation:可以为横向UIPageViewControllerNavigationOrientationHorizontal和纵向UIPageViewControllerNavigationOrientationVertical

  • options:该参数为词典。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:方法设置其内容视图。可以指定一次显示一个或两个视图控制器,其由spineLocationdoubleSided属性决定。动画结束后将显示传递给该方法的viewControllers。如果transition style为UIPageViewControllerTransitionStylePageCurl,传递给该方法的viewControllers将由spineLocationdoubleSided属性决定。

spineLocation doubleSided viewControllers参数
UIPageViewControllerSpineLocationMid YES 传入左侧和右侧需要显示的视图控制器
UIPageViewControllerSpineLocationMin

UIPageViewControllerSpineLocationMax
YES 传入正面、背面两侧显示的视图控制器。

背面视图控制用于翻页动画
UIPageViewControllerSpineLocationMin

UIPageViewControllerSpineLocationMax
NO 传入正面需要显示的视图控制器

5. UIPageViewControllerDelegate

UIPageViewController的委托必须遵守UIPageViewControllerDelegete协议,该协议中的方法允许委托在设备方向改变、用户导航到新页面时接收通知。对于page-curl style transition,可以在用户界面改变时提供不同的脊柱位置(spine location)。

RootViewController.m文件中,添加两个NSUInteger类型的属性,分别用来保存当前页码、下一页码。

@interface RootViewController () <UIPageViewControllerDelegate>

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

@end

实现UIPageViewControllerDelegete的协议方法,在用户滑动时更新页面内容:

// 手势导航开始前调用该方法。
- (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");
        }
    }
}

// 手势导航结束后调用该方法。
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    // 使用completed参数区分成功导航和中止导航。
    if (completed) {
        self.currentIndex = self.nextIndex;
    }
}

运行demo,滑动上面视图或点击底部UIPageControl,如下所示:

Scroll.gif

虽然在初始化时指定了page间距,但上面的gif中并没有显示,这是因为RootViewControllerDataViewController背景颜色一致所致,设置DataViewController视图背景颜色为brown color,再次运行demo:

UIPageViewControllerOptionInterPageSpacingKey

更新RootViewController.m中的viewDidLoad方法,设置transition style为page curl:

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

另外,实现UIPageViewControllerDelegate协议中的pageViewController: spineLocationForInterfaceOrientation:方法,根据设备状态调整spine location。

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
    if (UIInterfaceOrientationIsPortrait(orientation) || ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone)) {
        // 设备为phone,或portrait状态时,设置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时,设置spine为mid,pageViewController展示两个视图控制器。

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

        NSArray *viewControllers = [NSArray array];

        if (indexOfCurrentVC == 0 || indexOfCurrentVC % 2 == 0) {
            // 如果当前页为偶数,则显示当前页和下一页。
            UIViewController *nextVC = [self.model pageViewController:self.pageViewController viewControllerAfterViewController:currentVC];
            viewControllers = @[currentVC, nextVC];
        } else {
            // 如果当前页为奇数,则显示上一页和当前页。
            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协议中还有pageViewControllerSupportedInterfaceOrientations:方法,用来指定支持的全部方向。pageViewControllerPreferredInterfaceOrientationForPresentation:方法返回页面视图控制器的首选呈现方向。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容