iOS开发之多视图页面(可共用同一个页面)左右来回滑动切换视图的简单实现

多视图页面左右来回滑动切换效果

越来越多的客户端会遇到需要实现类似“头条”客户端那样的多视图页面左右来回滑动切换。
那么今天我们就来封装一下这个功能,实现这个功能。

先看需求:
1、点击标题按钮切换到对应的表视图上,或者左右滑动视图滑动到相应的视图上。
2、可共用一个控制器、可实现不同的控制器。

网上很多多事有多少个标题就有多少个控制器,然后for一下加入到数组,在把数组传进去创建。
那么,
今天我们封装,就不用那么麻烦了,直接可以共用一个控制器。满足很多客户端只是请求的参数不一样,但是页面是长得一样样的。

左右滑动切换视图

下面直接看封装的类:

//
//  XLBasePageController.h
//  XLPackKnowledge
//
//  Created by apple on 16/12/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import <UIKit/UIKit.h>

@class XLBasePageController;

#pragma mark View Pager Delegate
@protocol  XLBasePageControllerDelegate <NSObject>
@optional
///返回当前显示的视图控制器
-(void)viewPagerViewController:(XLBasePageController *)viewPager didFinishScrollWithCurrentViewController:(UIViewController *)viewController;
///返回当前将要滑动的视图控制器
-(void)viewPagerViewController:(XLBasePageController *)viewPager willScrollerWithCurrentViewController:(UIViewController *)ViewController;
@end

#pragma mark View Pager DataSource
@protocol XLBasePageControllerDataSource <NSObject>
@required
-(NSInteger)numberViewControllersInViewPager:(XLBasePageController *)viewPager;
-(UIViewController *)viewPager:(XLBasePageController *)viewPager indexViewControllers:(NSInteger)index;
-(NSString *)viewPager:(XLBasePageController *)viewPager titleWithIndexViewControllers:(NSInteger)index;
@optional
///设置控制器标题按钮的样式,不设置为默认
-(UIButton *)viewPager:(XLBasePageController *)viewPager titleButtonStyle:(NSInteger)index;
-(CGFloat)heightForTitleViewPager:(XLBasePageController *)viewPager;

///预留数据源
-(UIView *)headerViewForInViewPager:(XLBasePageController *)viewPager;
-(CGFloat)heightForHeaderViewPager:(XLBasePageController *)viewPager;
@end

@interface XLBasePageController : UIViewController
@property (nonatomic,weak) id<XLBasePageControllerDataSource> dataSource;
@property (nonatomic,weak) id<XLBasePageControllerDelegate> delegate;
///刷新
-(void)reloadScrollPage;

///默认选中
@property(nonatomic,assign) NSInteger selectIndex;

///按钮下划线的高度 字体大小 默认颜色  选中颜色
@property (nonatomic,assign) CGFloat lineWidth;
@property (nonatomic,strong) UIFont *titleFont;
@property (nonatomic,strong) UIColor *defaultColor;
@property (nonatomic,strong) UIColor *chooseColor;

@end

#pragma mark 标题按钮
@interface XLBasePageTitleButton : UIButton

@property (nonatomic,assign) CGFloat buttonlineWidth;

@end
//
//  XLBasePageController.m
//  XLPackKnowledge
//
//  Created by apple on 16/12/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "XLBasePageController.h"

@interface XLBasePageController ()<UIPageViewControllerDelegate,UIPageViewControllerDataSource>
{
    NSInteger totalVC;         //VC的总数量
    NSArray *VCArray;          //存放VC的数组
    NSArray *buttonArray;      //存放VC Button的数组
    UIView *headerView;        //头部视图
    CGRect oldRect;            //用来保存title布局的Rect
    XLBasePageTitleButton *oldButton;
    NSInteger currentVCIndex;  //当前VC索引
    
}
@property (nonatomic,strong) UIPageViewController *pageViewController;
@property (nonatomic,strong) UIScrollView *titleBGScroll;
@end

@implementation XLBasePageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.lineWidth = self.lineWidth>0?self.lineWidth:1.5;
    self.titleFont = self.titleFont?self.titleFont:[UIFont systemFontOfSize:14.0];
    self.defaultColor = self.defaultColor?self.defaultColor:[UIColor blackColor];
    self.chooseColor = self.chooseColor?self.chooseColor:[UIColor redColor];
    
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    [self.view addSubview:self.titleBackground];
    
}

-(UIPageViewController *)pageViewController
{
    if (!_pageViewController) {
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
    }
    return _pageViewController;
}

-(UIScrollView *)titleBackground
{
    if (!_titleBGScroll) {
        _titleBGScroll = [[UIScrollView alloc] init];
        _titleBGScroll.backgroundColor = [UIColor whiteColor];
        _titleBGScroll.showsHorizontalScrollIndicator = NO;
        _titleBGScroll.showsVerticalScrollIndicator = NO;
    }
    return _titleBGScroll;
}

-(void)setDataSource:(id<XLBasePageControllerDataSource>)dataSource
{
    _dataSource = dataSource;
    //[self reloadScrollPage];
}

-(void)reloadScrollPage
{
    if ([self.dataSource respondsToSelector:@selector(numberViewControllersInViewPager:)]) {
        oldRect = CGRectZero;
        totalVC = [self.dataSource numberViewControllersInViewPager:self];
        NSMutableArray *VCList = [NSMutableArray array];
        NSMutableArray *buttonList = [NSMutableArray array];
        for (int i = 0; i<totalVC; i++) {
            if ([self.dataSource respondsToSelector:@selector(viewPager:indexViewControllers:)]) {
                
                id viewcontroller = [self.dataSource viewPager:self indexViewControllers:i];
                if ([viewcontroller isKindOfClass:[UIViewController class]]) {
                    [VCList addObject:viewcontroller];
                }
            }

            if ([self.dataSource respondsToSelector:@selector(viewPager:titleWithIndexViewControllers:)]) {
                NSString *buttonTitle = [self.dataSource viewPager:self titleWithIndexViewControllers:i];
                if (buttonArray.count > i) {
                    [[buttonArray objectAtIndex:i] removeFromSuperview];
                }
                UIButton *button;
                if ([self.dataSource respondsToSelector:@selector(viewPager:titleButtonStyle:)])
                {
                    if ([[self.dataSource viewPager:self titleButtonStyle:i] isKindOfClass:[UIButton class]]) {
                        button = [self.dataSource viewPager:self titleButtonStyle:i];
                    }
                }else{
                    
                    XLBasePageTitleButton *autoButton = [[XLBasePageTitleButton alloc] init];
                    
                    autoButton.buttonlineWidth = self.lineWidth;
                    
                    [autoButton.titleLabel setFont:self.titleFont];
                    [autoButton setTitleColor:self.defaultColor forState:UIControlStateNormal];
                    [autoButton setTitleColor:self.chooseColor forState:UIControlStateSelected];
                    
                    button = autoButton;
                    
                }
                [button addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                
                
                button.frame = CGRectMake(oldRect.origin.x+oldRect.size.width, 0, [self textString:buttonTitle withFontHeight:20], [self.dataSource respondsToSelector:@selector(heightForTitleViewPager:)]?[self.dataSource heightForTitleViewPager:self]:0);
                oldRect = button.frame;
                [button setTitle:buttonTitle forState:UIControlStateNormal];
                [buttonList addObject:button];
                [_titleBGScroll addSubview:button];
                if (i == self.selectIndex) {
                    oldButton = [buttonList objectAtIndex:self.selectIndex];
                    oldButton.selected = YES;
                }
            }
        }
        //当所有按钮尺寸小于屏幕宽度的时候要重新布局
        if (buttonList.count && ((UIButton *)buttonList.lastObject).frame.origin.x + ((UIButton *)buttonList.lastObject).frame.size.width<self.view.frame.size.width)
        {
            oldRect = CGRectZero;
            CGFloat padding = self.view.frame.size.width-(((UIButton *)buttonList.lastObject).frame.origin.x + ((UIButton *)buttonList.lastObject).frame.size.width);
            for (XLBasePageTitleButton *button in buttonList) {
                button.frame = CGRectMake(oldRect.origin.x+oldRect.size.width, 0,button.frame.size.width+padding/buttonList.count, [self.dataSource respondsToSelector:@selector(heightForTitleViewPager:)]?[self.dataSource heightForTitleViewPager:self]:0);
                oldRect = button.frame;
            }
        }
        buttonArray = [buttonList copy];
        VCArray = [VCList copy];
    }
    if ([self.dataSource respondsToSelector:@selector(headerViewForInViewPager:)]) {
        [headerView removeFromSuperview];
        headerView = [self.dataSource headerViewForInViewPager:self];
        [self.view addSubview:headerView];
    }
    if (VCArray.count) {
        [_pageViewController setViewControllers:@[VCArray[self.selectIndex]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    }
}

-(void)titleButtonClick:(XLBasePageTitleButton *)sender
{
    oldButton.selected = NO;
    sender.selected = YES;
    oldButton = sender;
    NSInteger index = [buttonArray indexOfObject:sender];
    [_pageViewController setViewControllers:@[VCArray[index]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self scrollViewOffset:sender];
}

-(void)titleButtonConvert:(XLBasePageTitleButton *)sender
{
    oldButton.selected = NO;
    sender.selected = YES;
    oldButton = sender;
    [self scrollViewOffset:sender];
    
}

-(void)scrollViewOffset:(UIButton *)button
{
    if (!(_titleBGScroll.contentSize.width>CGRectGetWidth(self.view.frame))) {
        return;
    }
    if (CGRectGetMidX(button.frame)>CGRectGetMidX(self.view.frame)) {
        if (_titleBGScroll.contentSize.width<CGRectGetMaxX(self.view.frame)/2+CGRectGetMidX(button.frame)) {
            [_titleBGScroll setContentOffset:CGPointMake(_titleBGScroll.contentSize.width-CGRectGetWidth(self.view.frame), 0) animated:YES];
        }
        else{
            [_titleBGScroll setContentOffset:CGPointMake(CGRectGetMidX(button.frame)-CGRectGetWidth(self.view.frame)/2, 0) animated:YES];
        }
    }
    else{
        [_titleBGScroll setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}

#pragma mark -UIPageViewControllerDelegate
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if (completed) {
        if (currentVCIndex != [VCArray indexOfObject:previousViewControllers[0]]) {
            [self chooseTitleIndex:currentVCIndex];
            if ([self.delegate respondsToSelector:@selector(viewPagerViewController:didFinishScrollWithCurrentViewController:)]) {
                [self.delegate viewPagerViewController:self didFinishScrollWithCurrentViewController:[VCArray objectAtIndex:currentVCIndex]];
            }
        }
        
    }
}

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers
{
    currentVCIndex = [VCArray indexOfObject:pendingViewControllers[0]];
    if ([self.delegate respondsToSelector:@selector(viewPagerViewController:willScrollerWithCurrentViewController:)]) {
        [self.delegate viewPagerViewController:self willScrollerWithCurrentViewController:pageViewController.viewControllers[0]];
    }
}

#pragma mark -UIPageViewControllerDataSource
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSInteger index = [VCArray indexOfObject:viewController];
    if (index == 0 || index == NSNotFound) {
        return nil;
        
    }else{
        return VCArray[--index];
    }
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSInteger index = [VCArray indexOfObject:viewController];
    if (index == VCArray.count-1 || index == NSNotFound) {
        return nil;
        
    }else{
        return VCArray[++index];
    }
}

-(void)chooseTitleIndex:(NSInteger)index
{
    [self titleButtonConvert:buttonArray[index]];
}

-(void)viewDidLayoutSubviews
{
    headerView.frame = CGRectMake(0, self.topLayoutGuide.length, self.view.frame.size.width,[self.dataSource respondsToSelector:@selector(heightForHeaderViewPager:)]?[self.dataSource heightForHeaderViewPager:self]:0);
    
    _titleBGScroll.frame = CGRectMake(0, (headerView.frame.size.height)?headerView.frame.origin.y+headerView.frame.size.height:self.topLayoutGuide.length, self.view.frame.size.width,[self.dataSource respondsToSelector:@selector(heightForTitleViewPager:)]?[self.dataSource heightForTitleViewPager:self]:0);
    
    if (buttonArray.count) {
        
        _titleBGScroll.contentSize = CGSizeMake(((UIButton *)buttonArray.lastObject).frame.size.width+((UIButton *)buttonArray.lastObject).frame.origin.x, _titleBGScroll.frame.size.height);
    }
    
    _pageViewController.view.frame = CGRectMake(0, _titleBGScroll.frame.origin.y+_titleBGScroll.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-(_titleBGScroll.frame.origin.y+_titleBGScroll.frame.size.height));
}

#pragma mark 计算字体宽度
-(CGFloat)textString:(NSString *)text withFontHeight:(CGFloat)height
{
    CGFloat padding = 20;
    NSDictionary *fontAttribute = @{NSFontAttributeName : self.titleFont};
    CGSize fontSize = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:fontAttribute context:nil].size;
    return fontSize.width+padding;
}

@end

#pragma mark 标题按钮的属性设置
@implementation XLBasePageTitleButton
- (instancetype)init
{
    self = [super init];
    if (self) {
    
    }
    return self;
}

-(void)drawRect:(CGRect)rect
{
    if (self.selected) {
        CGFloat lineWidth = 1.0;
        CGColorRef color = self.titleLabel.textColor.CGColor;
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(ctx, color);
        CGContextSetLineWidth(ctx, lineWidth);
        CGContextMoveToPoint(ctx, 0, self.frame.size.height-lineWidth);
        CGContextAddLineToPoint(ctx, self.frame.size.width, self.frame.size.height-lineWidth);
        CGContextStrokePath(ctx);
    }
}

@end

项目需求,在预留头部视图不随滑动而滑动的效果,如果不需要,可以不实现该方法,默认是无头部视图的,效果图:

头部视图是固定的咯

那么如何使用呢?很简单,新建一个控制器继承:XLBasePageController,然后实现:
XLBasePageControllerDelegate、XLBasePageControllerDataSource

//
//  BaseScrollListVC.m
//  XLPackKnowledge
//
//  Created by apple on 16/12/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "BaseScrollListVC.h"
#import "ListVC.h"
#import "DetailVC.h"

@interface BaseScrollListVC () <XLBasePageControllerDelegate,XLBasePageControllerDataSource>

@property (nonatomic,strong) NSArray *titleArray;
@property (nonatomic,strong) UIView *headerView;

@end

@implementation BaseScrollListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _titleArray = @[@"全部",@"推荐",@"热点",@"附近",@"订阅",@"问答",@"社会",@"体育",@"财经"];
    
    self.delegate = self;
    self.dataSource = self;
    
    self.lineWidth = 2.0;//选中下划线宽度
    self.titleFont = [UIFont systemFontOfSize:16.0];
    self.defaultColor = [UIColor blackColor];//默认字体颜色
    self.chooseColor = [UIColor blueColor];//选中字体颜色
    self.selectIndex = 1;//默认选中第几页
    
    [self reloadScrollPage];
}

-(NSInteger)numberViewControllersInViewPager:(XLBasePageController *)viewPager
{
    return _titleArray.count;
}

-(UIViewController *)viewPager:(XLBasePageController *)viewPager indexViewControllers:(NSInteger)index
{
    if (index != 2) {
        ListVC *listVC = [[ListVC alloc] init];
        listVC.title = _titleArray[index];
        listVC.index = index;
        return listVC;
    }else{
        DetailVC *detailVC = [[DetailVC alloc] init];
        detailVC.title = _titleArray[index];
        detailVC.index = index;
        return detailVC;
    }
}

-(CGFloat)heightForTitleViewPager:(XLBasePageController *)viewPager
{
    return 50;
}

-(NSString *)viewPager:(XLBasePageController *)viewPager titleWithIndexViewControllers:(NSInteger)index
{
    return self.titleArray[index];
}

-(void)viewPagerViewController:(XLBasePageController *)viewPager didFinishScrollWithCurrentViewController:(UIViewController *)viewController
{
    self.title = viewController.title;
}

#pragma mark 预留--可不实现

-(UIView *)headerViewForInViewPager:(XLBasePageController *)viewPager
{
    return self.headerView;
}

-(CGFloat)heightForHeaderViewPager:(XLBasePageController *)viewPager
{
    return 100;
}

-(UIView *)headerView
{
    if (_headerView == nil) {
        _headerView = [[UIView alloc] init];
        _headerView.backgroundColor = [UIColor colorWithRed:120/255.0f green:210/255.0f blue:249/255.0f alpha:1];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, self.view.bounds.size.width, 40)];
        label.textColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:12.0];
        label.text = @"固定的头View,不可跟随滑动,可不显示";
        label.textAlignment = NSTextAlignmentCenter;
        [_headerView addSubview:label];
    }
    return _headerView;
}

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

@end
可不设置,都有默认值了

下面是几个可随便自定义的属性。

    self.lineWidth = 2.0;//选中下划线宽度
    self.titleFont = [UIFont systemFontOfSize:16.0];
    self.defaultColor = [UIColor blackColor];//默认字体颜色
    self.chooseColor = [UIColor blueColor];//选中字体颜色
    self.selectIndex = 1;//默认选中第几页

Demo下载地址,欢迎stars --> XLBasePage

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,376评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,016评论 4 62
  • 你点染了一根利群 是我的最爱和情怀 抽完了你走了 我捡起烟头猛的抽了一口 跟其他的烟一样 抽到了末尾 都是酸酸的
    illme阅读 339评论 0 2
  • 托网速慢的福,豆瓣首页的一则热门,恰好闯进视线。 名字简洁明了——《绿色火车》。 是个有些老的相册,创建上传于20...
    心平常_自非凡阅读 153评论 0 0