无限上拉效果

知乎上有一个无限上拉显示新页面,下拉显示上一个页面的功能,在用户体验上的确非常好,有类似功能的还有淘宝商品详情页面,小米有品的分类页面都有这样的应用,那这个功能是如何实现的呢,下面我们就进行简单分析。


QQ20181017-144043.gif

实现原理

通过上拉和下拉进行切换页面,切换页面通常可以使用转场动画来实现,可是如果使用push或者present的自定义转场来做,当dimiss或pop后,页面会被释放,这个对于平凡上拉下拉操作来说效率有点低,因此我们采用了addChildController来实现这个效果。

1、首先我们定义一个subViewController,这个就是我们进行上拉和下拉操作。

.h文件

#import <UIKit/UIKit.h>

@protocol SubViewControllerDelegate <NSObject>

@optional

- (void)pullingUpView:(UIView *)view;
- (void)pullingDownView:(UIView *)view;

@end
NS_ASSUME_NONNULL_BEGIN

@interface SubViewController : UIViewController
@property (nonatomic, weak) id<SubViewControllerDelegate>delegate;
@property(nonatomic, assign) CGFloat itemheight;
//- (void)uploadSubView;
@end

NS_ASSUME_NONNULL_END

.m文件

#import "SubViewController.h"
#import <UIView+SDAutoLayout.h>
#import "PingweiViewController.h"
static const NSInteger kOffSet = 100;

@interface SubViewController ()    <UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView * mScrollView;
@property (nonatomic, strong) UIView * subView;
@property (nonatomic, strong) SubViewController * subViewController;
@end

@implementation SubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor colorWithRed:(random()%255)/255.0 green:(random()%255)/255.0 blue:(random()%255)/255.0 alpha:1];
    [self.view addSubview:self.mScrollView];
     self.mScrollView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    NSLog(@"%s",__FUNCTION__);
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"%s",__FUNCTION__);

}

#pragma mark - <UICollectionView>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 20;
}

// The cell that is returned must be retrieved from a call to -    dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor=[UIColor colorWithRed:(arc4random()%256)/255.0 green:(arc4random()%256)/255.0 blue:(arc4random()%256)/255.0 alpha:1];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    PingweiViewController * pingwei=[[PingweiViewController alloc] init];
    [self.navigationController pushViewController:pingwei animated:YES];
}


#pragma mark - <ScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //    NSLog(@"");
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"end");
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{

    CGFloat offSetY= scrollView.contentOffset.y;
    //下拉
    if (offSetY<-kOffSet) {
    if (self.delegate &&[self.delegate respondsToSelector:@selector(pullingDownView:)]) {
            [self.delegate pullingDownView:self.view];
        }
    }
      //上拉
    CGFloat contentH=scrollView.contentSize.height-CGRectGetHeight(self.mScrollView.frame);
    if (offSetY-contentH>kOffSet) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(pullingUpView:)]) {
        [self.delegate pullingUpView:self.view];
        }
    }
}

#pragma mark - <setter and getter>
- (UIScrollView *)mScrollView{
    if (!_mScrollView) {
        UICollectionViewFlowLayout * layout=[[UICollectionViewFlowLayout alloc] init];
        layout.itemSize=CGSizeMake((self.view.frame.size.width-10)/2.0, self.itemheight);
        layout.minimumLineSpacing=5;
        layout.minimumInteritemSpacing=5;
        _mScrollView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:layout];
        _mScrollView.delegate=self;
        _mScrollView.dataSource=self;
        [_mScrollView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        _mScrollView.backgroundColor=[UIColor whiteColor];
    }
    return _mScrollView;
}
@end

2、在ViewController中添加ChildController,并将ChildConroller的View添加self.View上。为了能够实现切换,我们定义了一个Container视图,类型是UIScrollView,这样可以通过设置ContentOffset的值来实现切换动画。具体实现如下

#import "FengLeiViewController.h"
#import "SubViewController.h"
#import <UIView+SDAutoLayout.h>
@interface FengLeiViewController ()<UIScrollViewDelegate,SubViewControllerDelegate>
@property (nonatomic, strong) UIView * subView;
@property (nonatomic, strong) SubViewController * subViewController;
@property (nonatomic, strong) UIScrollView * mContainer;
@property (nonatomic, assign) NSInteger totalCount;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) NSMutableArray * dataArray;
@end

@implementation FengLeiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"分类";
    _dataArray=[[NSMutableArray alloc] init];
    self.totalCount=5;
    for (int i=0; i<self.totalCount; i++) {
        [_dataArray addObject:[NSString stringWithFormat:@"第%@页",@(i+1)]];
    }
    self.currentPage=0;
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.mContainer];
    self.mContainer.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    SubViewController * subVC0=[[SubViewController alloc] init];
    self.title=self.dataArray[self.currentPage];
    subVC0.delegate=self;
    subVC0.itemheight=100;
    [self addChildViewController:subVC0];

    [self.mContainer addSubview:subVC0.view];
    subVC0.view.sd_layout.leftSpaceToView(self.mContainer, 0)
    .topSpaceToView(self.mContainer, 0)
    .rightSpaceToView(self.mContainer, 0)
    .bottomSpaceToView(self.mContainer, 0);

}

#pragma mark - <>
- (void)pullingDownView:(UIView *)view{
    if (self.currentPage>0) {
        [UIView animateWithDuration:0.7 animations:^{
            self.mContainer.contentOffset=CGPointMake(0, (self.currentPage-1)*CGRectGetHeight(self.view.frame));
        } completion:^(BOOL finished) {
        }];;
    }
}

- (void)pullingUpView:(UIView *)view{

    NSInteger count= self.childViewControllers.count;
    if (self.currentPage>=(self.totalCount-1)) {
        return;
    }
    [UIView animateWithDuration:0.7 animations:^{
        self.mContainer.contentOffset=CGPointMake(0, (self.currentPage+1)*(CGRectGetHeight(self.view.frame)));
    } completion:^(BOOL finished) {
      if (self.currentPage>=count&&self.currentPage<(self.totalCount)) {
        dispatch_async(dispatch_get_main_queue(), ^{
            SubViewController * sub=[[SubViewController alloc] init];
            
            sub.itemheight=150;
            sub.delegate=self;
            [self addChildViewController:sub];
            [self.mContainer addSubview:sub.view];
                self.mContainer.contentSize=CGSizeMake(self.mContainer.width_sd, self.mContainer.height_sd*(self.childViewControllers.count));
                sub.view.sd_layout.leftSpaceToView(self.mContainer, 0)
            .topSpaceToView(view, 0)
            .rightSpaceToView(self.mContainer, 0)
            .heightIs(CGRectGetHeight(self.view.frame));
            });
        }
    }];
}
#pragma mark - <ScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"****** page  %@",@(scrollView.contentOffset.y/scrollView.frame.size.height    ));
    self.currentPage=scrollView.contentOffset.y/scrollView.frame.size.height;
    self.title=self.dataArray[self.currentPage];
}



#pragma mark - <setter and getter>

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

推荐阅读更多精彩内容