iOS UIPageViewController 使用

主要视图控制器MyPageViewController

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyPageViewController : UIViewController

@end

NS_ASSUME_NONNULL_END

#import "MyPageViewController.h"
#import "MyViewController.h" /// 复用的controller
#import "MyCollectionTitleCell.h"/// 标题栏使用的collectionviewcell

@interface MyPageViewController ()<UIPageViewControllerDelegate,UIPageViewControllerDataSource,UICollectionViewDelegate,UICollectionViewDataSource>{

 //// 记录当前页 当前标题位置
 NSInteger gl_currentIndex;

}

@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, strong) NSMutableArray *controllersArr;/// 控制器数组
@property (nonatomic, strong) NSMutableArray *titleArray; /// 标题数组
@property (nonatomic, strong) UICollectionView *titleCollectionView; /// 标题collectionview
@end


@implementation MyPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.controllersArr = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    //// 如果controller布局相同则循环创建MyViewController 添加进数组,,如果controller 布局不同 那就创建多个不同controller依次添加数组
    for (int i = 0; i < 10; i++) {
        MyViewController *con = [[MyViewController alloc]init];
        [self.controllersArr addObject:con];
        NSString *str = [NSString stringWithFormat:@"第 %d 页", i+1];
         con.titleStr = str;
        [self.titleArray addObject:str];
        
    }
    
    [self createCollectionView];
    [self createPageViewController];
    [self setTheFirstPage];
}

/// 创建标题collectionview
- (void)createCollectionView{
    UICollectionViewFlowLayout *lay = [[UICollectionViewFlowLayout alloc] init];
    lay.itemSize = CGSizeMake(60, 30);
    lay.minimumLineSpacing = 0;
    lay.minimumInteritemSpacing = 0;
    lay.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.titleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 34, 375, 30) collectionViewLayout:lay];
    self.titleCollectionView.showsHorizontalScrollIndicator = NO;
    self.titleCollectionView.backgroundColor = [UIColor whiteColor];
    self.titleCollectionView.delegate = self;
    self.titleCollectionView.dataSource = self;
    [self.titleCollectionView registerClass:[MyCollectionTitleCell class] forCellWithReuseIdentifier:@"titleReuse"];
    [self.navigationController.view addSubview:self.titleCollectionView];
}

//// 标题collectionview的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.titleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionTitleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"titleReuse" forIndexPath:indexPath];
    cell.title_Label.text = self.titleArray[indexPath.row];
    
    if (indexPath.row == gl_currentIndex) {
        cell.title_Label.textColor = [UIColor orangeColor];
    }else{
        cell.title_Label.textColor = [UIColor blackColor];
    }
    return cell;
}

//// 点击标题左右切换视图控制器------------再也不用看到好几个中间页面从屏幕快速闪过了------
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIViewController *vc = [self.controllersArr objectAtIndex:indexPath.row];
    if (indexPath.row > gl_currentIndex) {
        [self.pageViewController setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished) {
            
        }];
        
    } else {
        
        [self.pageViewController setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:^(BOOL finished) {
            
        }];
    }
    gl_currentIndex = indexPath.row;
    NSIndexPath *path = [NSIndexPath indexPathForRow:gl_currentIndex inSection:0];
    [self.titleCollectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    [self.titleCollectionView reloadData];
}

/// 创建pageViewController
- (void)createPageViewController {
    NSDictionary *option = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:0] forKey:UIPageViewControllerOptionInterPageSpacingKey];
    _pageViewController = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:option];
    _pageViewController.delegate = self;
    _pageViewController.dataSource = self;
    [self addChildViewController:_pageViewController];
    [self.view addSubview:_pageViewController.view];
    
}

/// 展示上一页
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSInteger index = [self.controllersArr indexOfObject:viewController];
    if (index == 0 || (index == NSNotFound)) {
        return nil;
    }
    
    index--;
    return [self.controllersArr objectAtIndex:index];
}

/// 展示下一页
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSInteger index = [self.controllersArr indexOfObject:viewController];
    if (index == self.controllersArr.count - 1 || (index == NSNotFound)) {
        return nil;
    }
    
    index++;
    return [self.controllersArr objectAtIndex:index];
}

/// 将要滑动切换的时候
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    UIViewController *nextVC = [pendingViewControllers firstObject];
    NSInteger index = [self.controllersArr indexOfObject:nextVC];
    gl_currentIndex = index;
}

/// 滑动结束后
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:gl_currentIndex inSection:0];
        [self.titleCollectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        [self.titleCollectionView reloadData];
        
        NSLog(@">>>>>>>>> %ld", (long)gl_currentIndex);
    }
}

/// 设置默认显示的是哪个页面(controller)
- (void)setTheFirstPage{
    UIViewController *vc = [self.controllersArr objectAtIndex:gl_currentIndex];
    [self.pageViewController setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

@end

Common 控制器 可根据不同需求单独定制


#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyViewController : UIViewController

@property (nonatomic, copy) NSString *titleStr;

@end

NS_ASSUME_NONNULL_END

#import "MyViewController.h"

@interface MyViewController ()

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    mainLabel.textAlignment = NSTextAlignmentCenter;
    mainLabel.font = [UIFont systemFontOfSize:30];
    mainLabel.textColor = [UIColor orangeColor];
    mainLabel.text = self.titleStr;
    [self.view addSubview:mainLabel];
}


@end

滑动标题cell

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyCollectionTitleCell : UICollectionViewCell

/** title_Label */
@property (nonatomic, strong) UILabel *title_Label;

@end

NS_ASSUME_NONNULL_END

#import "MyCollectionTitleCell.h"


@implementation MyCollectionTitleCell


- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        UILabel *title_Label = [[UILabel alloc] init];
        title_Label.font = [UIFont systemFontOfSize:12];
        title_Label.textAlignment = NSTextAlignmentCenter;
        title_Label.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
        self.title_Label = title_Label;
        [self.contentView addSubview:title_Label];
        
    }
    
    return self;
}

@end

UIPageViewController效果可用于左右滑动请求新数据

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