自定义下拉刷新与上拉加载控件

1.headerView不要用tableView的tableHeaderView头视图 , 因为一般的头视图会用做广告条使用 ;
2.调整UIEdgeInsets属性来设置headerView上的headerLabel的变化 , 做到下拉与回退的效果 ;
3.本示例代码中的数据都是mock的假数据 ;
4.设置一个BOOL属性记录是否正在刷新,正在加载的判断 , 如果正在刷新或者加载的状态我就return , 防止误操作 ;
5.数据请求成功后要回退到原来的位置 , 数据也要reloadData , 请求也要结束 ;

#import "TestViewController.h"

@interface AllViewController ()
@property (nonatomic , strong) UIView *footerView ;
@property (nonatomic , strong) UILabel *footerLabel ;
@property (nonatomic , strong) UIView *headerView ;
@property (nonatomic , strong) UILabel *headerLabel ;
//记录上拉加载控件是否正在刷新
@property (nonatomic , assign , getter=isFooterRefreshing) BOOL footerRefreshing ;
//记录下拉刷新控件是否正在刷新
@property (nonatomic , assign , getter=isHeaderRefreshing) BOOL headerRefreshing ;
@property (nonatomic , assign) NSInteger dataCount ;

@end

@implementation AllViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataCount = 30 ;
    self.view.backgroundColor = BSRandomColor ;
    self.tableView.contentInset = ContentInset ;
    //滚动条的内边距与tableView的内边距相同:
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset ;
    //tabBarButton按钮监听:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarButtonDidRepeatClick) name:BSTabBarButtonDidRepeatClickNotification object:nil] ;
    //titleButton按钮监听:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(titleButtonDidRepeatClick) name:BSTitleButtonDidRepeatClickNotification object:nil] ;
    //上拉加载控件:
    [self setupRefresh] ;
    
}

#pragma mark - 自定义上拉加载控件
- (void)setupRefresh {
    
    //广告条:
    UILabel *ADLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 30)] ;
    ADLabel.text = @"假装有广告" ;
    ADLabel.textColor = [UIColor blackColor] ;
    ADLabel.backgroundColor = [UIColor whiteColor] ;
    ADLabel.textAlignment = NSTextAlignmentCenter ;
    self.tableView.tableHeaderView = ADLabel ;
    
    //header:
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, -50, self.tableView.width, 50)] ;
    headerView.backgroundColor = [UIColor redColor] ;
    self.headerView = headerView ;
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:headerView.bounds] ;
    headerLabel.backgroundColor = [UIColor blackColor] ;
    headerLabel.textColor = [UIColor redColor] ;
    headerLabel.text = @"下拉加载更多数据..." ;
    headerLabel.textAlignment = NSTextAlignmentCenter ;
    self.headerLabel = headerLabel ;
    [headerView addSubview:headerLabel] ;
    [self.tableView addSubview:headerView] ;
    
    //footer:
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, 35)] ;
    self.footerView = footerView ;
    UILabel *footerLabel = [[UILabel alloc] init] ;
    footerLabel.frame = footerView.bounds ;
    footerLabel.backgroundColor = [UIColor redColor] ;
    footerLabel.text = @"上拉加载更多" ;
    footerLabel.textAlignment = NSTextAlignmentCenter ;
    self.footerLabel = footerLabel ;
    [footerView addSubview:footerLabel] ;
    self.tableView.tableFooterView = footerView ;
}


#pragma mark - tabBarButton按钮被重复点击了
- (void)tabBarButtonDidRepeatClick {
    //如果当前控制器不在主window上 , 说明点击的不是精华按钮:
    if (self.view.window == nil) return ;
    //如果是精华按钮,但是还需要判断是不是全部模块:
    if (self.tableView.scrollsToTop == NO) return ;
    BSLog(@"%@ -- 刷新数据" , self.class) ;
}


#pragma mark - titleButton按钮被重复点击了
- (void)titleButtonDidRepeatClick {
    //与tabBarButtonDidRepeatClick的方法相同:
    [self tabBarButtonDidRepeatClick] ;
}


#pragma mark - 移除所有通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self] ;
}


#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.footerView.hidden = (self.dataCount == 0) ;
    return self.dataCount ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *const AllCell = @"AllCell" ;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:AllCell] ;
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AllCell] ;
        cell.backgroundColor = [UIColor clearColor] ;
    }
    cell.textLabel.text = [NSString stringWithFormat:@"test --%@-- %zd" ,[self class] , indexPath.row] ;
    return cell ;
}


#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self handleHeader] ;
    [self handleFooter] ;
}

//用户松开scrollView时调用该方法(停止拖拽方法):
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.isHeaderRefreshing) return ;
    //可以通过文字来判断:
    //可以通过背景色:
    //可以通过偏移量来判断:
    //感觉偏移量更正规的说:
    CGFloat offsetY = - (64 + 35 + 50) ;
    if (self.tableView.contentOffset.y <= offsetY){
        //进入下拉刷新状态 :
        self.headerRefreshing = YES ;
        self.headerLabel.text = @"正在加载新数据..." ;
        self.headerLabel.textColor = [UIColor redColor] ;
        self.headerLabel.backgroundColor = [UIColor blueColor] ;
        //增大内边距:
        [UIView animateWithDuration:0.25 animations:^{
            UIEdgeInsets inset = self.tableView.contentInset  ;
            inset.top += self.headerView.height ;
            self.tableView.contentInset = inset ;
        }] ;

        //模拟数据返回成功:
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //服务器的数据回来了!
            self.dataCount = 20 ;
            [self.tableView reloadData] ;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //2s后结束刷新:
                [UIView animateWithDuration:0.25 animations:^{
                    UIEdgeInsets inset = self.tableView.contentInset ;
                    inset.top -= self.headerView.height ;
                    self.tableView.contentInset = inset ;
                }] ;
                //文字和背景色等都要还原:
                self.headerLabel.backgroundColor = [UIColor blackColor] ;
                self.headerLabel.textColor = [UIColor redColor] ;
                self.headerLabel.text = @"下拉加载更多数据..." ;
                self.headerLabel.textAlignment = NSTextAlignmentCenter ;
                //此时还要把当前控件的是否正在刷新状态改为NO:
                self.headerRefreshing = NO ;
            });
        });
    }
}


#pragma mark - 处理header
- (void)handleHeader {
    //如果正在下拉刷新直接返回:
    //防止在处理下拉加载数据的时候再次进入下面的代码内容:
    if (self.isHeaderRefreshing) return ;
    //当scrollView的偏移量小于等于offsetY的时候 , 说明下拉刷新控件完全出现了!
    CGFloat offsetY = - (64 + 35 + 50) ;
    if (self.tableView.contentOffset.y <= offsetY) {
        self.headerLabel.backgroundColor = [UIColor yellowColor] ;
        self.headerLabel.textColor = [UIColor blueColor] ;
        self.headerLabel.text = @"松开立即刷新..." ;
        self.headerLabel.textAlignment = NSTextAlignmentCenter ;
    } else {
        //退回去之后还要返回原来的颜色:
        self.headerLabel.backgroundColor = [UIColor blackColor] ;
        self.headerLabel.textColor = [UIColor redColor] ;
        self.headerLabel.text = @"下拉加载更多数据..." ;
        self.headerLabel.textAlignment = NSTextAlignmentCenter ;
    }
}


#pragma mark - 处理footer
- (void)handleFooter {
    //如果内容还没有出现 , 还是0值 , 那么就return ;否则会在一开始就显示"footerView完全出现"的情况 ;
    if (self.tableView.contentSize.height == 0) return ;
    CGFloat offsetY = self.tableView.contentSize.height + self.tableView.contentInset.bottom - self.tableView.height ;
    //如果正在刷新 , 说明正在发请求给服务器 , 就没必要再次进入这个重复发送请求的状态了!
    if (self.isFooterRefreshing) return ;
    if (self.tableView.contentOffset.y >=offsetY) {
        BSLog(@"footerView完全出现") ;
        self.footerRefreshing = YES ;
        //进入刷新状态:
        self.footerLabel.text = @"正在加载更多数据..." ;
        self.footerLabel.backgroundColor = [UIColor blueColor] ;
        BSLog(@"发送请求给服务器...") ;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 2秒后服务器返回数据成功:
            self.dataCount += 5 ;
            [self.tableView reloadData] ;
            // 1.结束刷新:
            self.footerRefreshing =NO ;
            //文字 , 颜色等细部UI都要改回去:
            self.footerLabel.backgroundColor = [UIColor redColor] ;
            self.footerLabel.text = @"上拉加载更多" ;
        });
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

愿编程让这个世界更美好

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

推荐阅读更多精彩内容

  • 翻译自“Collection View Programming Guide for iOS” 0 关于iOS集合视...
    lakerszhy阅读 3,723评论 1 22
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 一.上拉刷新 1.为什么要做上拉刷新? 想要看一些旧的(更多)数据,就需要上拉刷新,加载更多数据 2.上拉刷新永远...
    尕小天阅读 918评论 0 5
  • 如果在一个不经意的抬头,看到了心心念念却好久不见的人,你会是怎样的心情? 忽然就是在一个不经意的抬头再次...
    羿十一阅读 1,410评论 24 15
  • 单位举办迎七一诗歌朗诵比赛,我踊跃报名了。和同事们一起参加四个人的集体朗诵。我们朗诵的内容是著名的青年作家高原红老...
    自在心灵空间阅读 444评论 0 2