MJRefresh的底層實現(xiàn)原理

#import "ViewController.h"
#import "MJExtension.h"
#import "AFNetworking.h"
#import "UIView+Frame.h"
#import "TopicItem.h"

@interface ViewController ()

//* 請求管理者 
@property (nonatomic, weak) AFHTTPSessionManager *mgr;
/** 全部的帖子數(shù)據(jù) */
@property (nonatomic, strong) NSMutableArray *topics;
/** 用來加載下一頁數(shù)據(jù) */
@property (nonatomic, copy) NSString *maxtime;

/******** 下拉刷新-header ********/
/** 下拉刷新控件 */
@property (nonatomic, weak) UIView *header;
/** 下拉刷新控件里面的文字 */
@property (nonatomic, weak) UILabel *headerLabel;
/** 是否為"松開立即刷新" */
@property(nonatomic, assign, getter=isWillLoadingNewData) BOOL willLoadingNewData;
/** 是否為"正在刷新" */
@property(nonatomic, assign, getter=isLoadingNewData) BOOL loadingNewData;
/******** 下拉刷新-header ********/

/******** 上拉刷新-footer ********/
/** 上拉刷新控件 */
@property (nonatomic, weak) UIView *footer;
/** 上拉刷新控件里面的文字 */
@property (nonatomic, weak) UILabel *footerLabel;
/** 是否正在加載更多數(shù)據(jù) */
@property(nonatomic, assign, getter=isLoadingMoreData) BOOL loadingMoreData;
/******** 上拉刷新-footer ********/

@end

@implementation ViewController

#pragma mark - 懶加載
- (AFHTTPSessionManager *)mgr
{
    if (!_mgr) {
        _mgr = [AFHTTPSessionManager manager];
    }
    return _mgr;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.contentInset = UIEdgeInsetsMake(61, 0, 0, 0);

    // 集成刷新控件
    [self setUpRefresh];

    [self loadNewTopics];
}

/**
 * 集成刷新控件
 */
- (void)setUpRefresh
{
    // 下拉刷新:加載最新的數(shù)據(jù)
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = [UIColor yellowColor];
    header.height = 60;
    header.width = self.tableView.width;
    header.y = - header.height;
    [self.tableView addSubview:header];
    self.header = header;

    UILabel *headerLabel = [[UILabel alloc] init];
    headerLabel.text = @"下拉可以刷新";
    headerLabel.width = self.tableView.width;
    headerLabel.height = header.height;
    headerLabel.textAlignment = NSTextAlignmentCenter;
    [header addSubview:headerLabel];
    self.headerLabel = headerLabel;

    // 上拉刷新:加載更多的數(shù)據(jù)
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = [UIColor orangeColor];
    footer.height = 35;
    footer.hidden = YES;
    self.tableView.tableFooterView = footer;
    self.footer = footer;

    UILabel *footerLabel = [[UILabel alloc] init];
    footerLabel.text = @"上拉可以加載更多";
    footerLabel.width = self.tableView.width;
    footerLabel.height = footer.height;
    footerLabel.textAlignment = NSTextAlignmentCenter;
    [footer addSubview:footerLabel];
    self.footerLabel = footerLabel;
}

#pragma mark - 數(shù)據(jù)處理
/**
 * 加載最新的帖子數(shù)據(jù)
 */
- (void)loadNewTopics
{
    // 拼接請求參數(shù)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @"1";

    // 發(fā)送請求
    [self.mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 存儲maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];

        // 字典數(shù)組 -> 模型數(shù)組
        self.topics = [TopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];

        // 刷新表格
        [self.tableView reloadData];

        // 結束刷新
        self.loadingNewData = NO;
        // 恢復頂部的內(nèi)邊距
        [UIView animateWithDuration:0.25 animations:^{
            UIEdgeInsets inset = self.tableView.contentInset;
            inset.top -= self.header.height;
            self.tableView.contentInset = inset;
        }];

        // 有數(shù)據(jù)了
        self.footer.hidden = NO;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"請求失敗 - %@", error);
        // 結束刷新
        self.loadingNewData = NO;
        // 恢復頂部的內(nèi)邊距
        [UIView animateWithDuration:0.25 animations:^{
            UIEdgeInsets inset = self.tableView.contentInset;
            inset.top -= self.header.height;
            self.tableView.contentInset = inset;
        }];
    }];
}

/**
 * 加載更多的帖子數(shù)據(jù)
 */
- (void)loadMoreTopics
{
    // 拼接請求參數(shù)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @"1";
    parameters[@"maxtime"] = self.maxtime;

    // 發(fā)送請求
    [self.mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 存儲maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];

        // 字典數(shù)組 -> 模型數(shù)組
        NSArray *moreTopics = [TopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.topics addObjectsFromArray:moreTopics];

        // 刷新表格
        [self.tableView reloadData];

        // 結束刷新
        self.loadingMoreData = NO;
        self.footerLabel.text = @"上拉可以加載更多";
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"請求失敗 - %@", error);

        // 結束刷新
        self.loadingMoreData = NO;
        self.footerLabel.text = @"上拉可以加載更多";
    }];
}

#pragma mark - 代理方法
/**
 * 當scrollView在滾動,就會調(diào)用這個代理方法
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 處理下拉刷新
    [self dealLoadNewData];

    // 處理上拉加載更多
    [self dealLoadMoreData];
}

/**
 * 當用戶手松開(停止拖拽),就會調(diào)用這個代理方法
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.willLoadingNewData == NO || self.loadingNewData) return;

    // 增加頂部的內(nèi)邊距
    [UIView animateWithDuration:0.25 animations:^{
        UIEdgeInsets inset = self.tableView.contentInset;
        inset.top += self.header.height;
        self.tableView.contentInset = inset;
    }];

    // 修改文字
    self.headerLabel.text = @"正在刷新數(shù)據(jù)...";

    // 正在刷新
    self.loadingNewData = YES;

    // 發(fā)送請求
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self loadNewTopics];
    });
}

/**
 * 處理下拉刷新
 */
- (void)dealLoadNewData
{
    if (self.loadingNewData) return;

    CGFloat offsetY =  - (64 + self.header.height);
    if (self.tableView.contentOffset.y <= offsetY) {
        self.headerLabel.text = @"松開立即刷新";
        self.willLoadingNewData = YES;
    } else {
        self.headerLabel.text = @"下拉可以刷新";
        self.willLoadingNewData = NO;
    }
}

/**
 * 處理上拉加載更多
 */
- (void)dealLoadMoreData
{
    // 如果沒有數(shù)據(jù) 或者 正在上拉刷新, 直接返回
    if (self.topics.count == 0 || self.loadingMoreData) return;

    CGFloat offsetY = self.tableView.contentSize.height + self.tableView.contentInset.bottom - self.tableView.height;
    if (self.tableView.contentOffset.y >= offsetY) {
        self.loadingMoreData = YES;

        // 更改文字
        self.footerLabel.text = @"正在加載更多的數(shù)據(jù)...";

        // 加載更多的帖子數(shù)據(jù)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadMoreTopics];
        });
    }
}

#pragma mark - 數(shù)據(jù)源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }

    TopicItem *item = self.topics[indexPath.row];
    cell.textLabel.text = item.name;
    cell.detailTextLabel.text = item.text;

    return cell;
}
@end
**效果**

實現(xiàn)原理
在tableView上加上一個View跪妥,注意不是headerView,而是一個Y值為負數(shù)的普通View声滥,下拉時候監(jiān)聽偏移量,改變View的內(nèi)容顯示纽疟。在tableView下面加上一個footerView憾赁,監(jiān)聽偏移量,當footerView完全顯示的時候加載更多數(shù)據(jù)蟆肆》溃基本代碼已貼枚冗,有不清楚的可以討論交流蛇损。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市股囊,隨后出現(xiàn)的幾起案子床玻,更是在濱河造成了極大的恐慌,老刑警劉巖贫堰,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件待牵,死亡現(xiàn)場離奇詭異,居然都是意外死亡偎行,警方通過查閱死者的電腦和手機蛤袒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門膨更,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人珍德,你說我怎么就攤上這事矗漾。” “怎么了泵琳?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵虑稼,是天一觀的道長。 經(jīng)常有香客問我,道長啦桌,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任且改,我火速辦了婚禮板驳,結果婚禮上若治,老公的妹妹穿的比我還像新娘。我一直安慰自己礼烈,他們只是感情好婆跑,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著犀忱,像睡著了一般扶关。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鲫寄,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天地来,我揣著相機與錄音熙掺,去河邊找鬼。 笑死币绩,一個胖子當著我的面吹牛府阀,可吹牛的內(nèi)容都是我干的芽突。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼田巴,長吁一口氣:“原來是場噩夢啊……” “哼壹哺!你這毒婦竟也來了艘刚?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤箩朴,失蹤者是張志新(化名)和其女友劉穎隧饼,沒想到半個月后静陈,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡拐格,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年捏浊,在試婚紗的時候發(fā)現(xiàn)自己被綠了金踪。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片牵敷。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖靶瘸,靈堂內(nèi)的尸體忽然破棺而出怨咪,到底是詐尸還是另有隱情,我是刑警寧澤唉匾,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布匠楚,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏益咬。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一幽告、第九天 我趴在偏房一處隱蔽的房頂上張望冗锁。 院中可真熱鬧嗤栓,春花似錦、人聲如沸茉帅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽钮呀。三九已至,卻和暖如春爽醋,著一層夾襖步出監(jiān)牢的瞬間土匀,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工田度, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人镇饺。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓送讲,卻偏偏與公主長得像奸笤,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子哼鬓,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容